package com.sxjh.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.cglib.CglibUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.sxjh.common.FinanceUtil;
import com.sxjh.entity.Backfill;
import com.sxjh.entity.Settlement;
import com.sxjh.entity.TruckingOrderDetails;
import com.sxjh.entity.TruckingOrderTear;
import com.sxjh.entity.bo.*;
import com.sxjh.entity.param.*;
import com.sxjh.entity.result.*;
import com.sxjh.mapper.*;
import com.sxjh.service.*;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.Collator;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Year;
import java.time.YearMonth;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class FinanceServiceImpl implements FinanceService {

    private Logger logger = LoggerFactory.getLogger(FinanceServiceImpl.class);

    @Autowired
    private MethylAlcoholMapper methylAlcoholMapper;

    @Autowired
    private ChemicalMapper chemicalMapper;

    @Autowired
    private FinanceMapper financeMapper;

//  @Autowired
//  private ContractService contractService;

    @Autowired
    private SettlementService settlementService;

    @Autowired
    private SettlementMapper settlementMapper;

    @Autowired
    private VariationLogService variationLogService;

//  @Autowired
//  private ContractMapper contractMapper;

    @Autowired
    private BackfillService backfillService;

    @Autowired
    private TruckingOrderDetailsMapper truckingOrderDetailsMapper;

    @Autowired
    private TruckingOrderTearService truckingOrderTearService;

    @Autowired
    private TruckingOrderTearMapper truckingOrderTearMapper;

    @Autowired
    private TruckingOrderDetailsService truckingOrderDetailsService;


    // 化工辅料
    @Override
    public List<MethylAlcoholListResult> list(MethylAlcoholListParam param) {
        List<MethylAlcoholListResult> list = methylAlcoholMapper.list(param);
        // 合计
        MethylAlcoholListResult entity = new MethylAlcoholListResult();
        entity.setCompanyName("合计");
        entity.setWeighbridgeWeight(new BigDecimal(0));
        entity.setSettlementPriceSum(new BigDecimal(0));
        entity.setSettlementPriceSumNo(new BigDecimal(0));
        entity.setVehCount(0);
        entity.setNetWeight(new BigDecimal(0));
        entity.setVehCount(0);
        int serialNumber = 0;
        for (MethylAlcoholListResult item : list) {
            serialNumber++;
            if (item.getWeighbridgeWeight() == null) item.setWeighbridgeWeight(new BigDecimal(0));
            if (item.getSettlementPrice() == null) item.setSettlementPrice(new BigDecimal(0));
            if (item.getSettlementPriceNo() == null) item.setSettlementPriceNo(new BigDecimal(0));
            if (item.getSettlementPriceSum() == null) item.setSettlementPriceSum(new BigDecimal(0));
            if (item.getSettlementPriceSumNo() == null) item.setSettlementPriceSumNo(new BigDecimal(0));
            // 计算合计
            entity.setWeighbridgeWeight(entity.getWeighbridgeWeight().add(item.getWeighbridgeWeight()));
            entity.setSettlementPriceSum(entity.getSettlementPriceSum().add(item.getSettlementPriceSum()));
            entity.setSettlementPriceSumNo(entity.getSettlementPriceSumNo().add(item.getSettlementPriceSumNo()));
            entity.setVehCount(entity.getVehCount() + item.getVehCount());
            entity.setNetWeight(entity.getNetWeight().add(item.getNetWeight()));
            item.setSerialNumber(serialNumber);
        }
//        list.add(entity);
        return list;
    }

    // 硫酸
    @Override
    public List<MethylAlcoholListResult> list3(MethylAlcoholListParam param) {
        List<MethylAlcoholListResult> list = financeMapper.list(param);
        // 合计
        MethylAlcoholListResult entity = new MethylAlcoholListResult();
        entity.setMaterialName("合计");
        entity.setWeighbridgeWeight(new BigDecimal(0));
        entity.setSettlementPriceSum(new BigDecimal(0));
        entity.setSettlementPriceSumNo(new BigDecimal(0));
        entity.setVehCount(0);
        entity.setNetWeight(new BigDecimal(0));
        for (MethylAlcoholListResult item : list) {
            if (item.getWeighbridgeWeight() == null) item.setWeighbridgeWeight(new BigDecimal(0));
            if (item.getSettlementPrice() == null) item.setSettlementPrice(new BigDecimal(0));
            if (item.getSettlementPriceNo() == null) item.setSettlementPriceNo(new BigDecimal(0));
            if (item.getSettlementPriceSum() == null) item.setSettlementPriceSum(new BigDecimal(0));
            if (item.getSettlementPriceSumNo() == null) item.setSettlementPriceSumNo(new BigDecimal(0));
            if (item.getNetWeight() == null) item.setNetWeight(new BigDecimal(0));
            // 计算合计
            entity.setWeighbridgeWeight(entity.getWeighbridgeWeight().add(item.getWeighbridgeWeight()));
            entity.setSettlementPriceSum(entity.getSettlementPriceSum().add(item.getSettlementPriceSum()));
            entity.setSettlementPriceSumNo(entity.getSettlementPriceSumNo().add(item.getSettlementPriceSumNo()));
            entity.setVehCount(entity.getVehCount() + item.getVehCount());
            entity.setNetWeight(entity.getNetWeight().add(item.getNetWeight()));
        }
        list.add(entity);
        return list;
    }

    // 炭黑
    @Override
    public List<MethylAlcoholListResult> list4(Finance6ListParam param) {
        List<MethylAlcoholListResult> list = financeMapper.list2(param);
        MethylAlcoholListResult entity = new MethylAlcoholListResult();
        entity.setWeighbridgeWeight(new BigDecimal(0));
        entity.setSettlementPriceSum(new BigDecimal(0));
        entity.setSettlementPriceSumNo(new BigDecimal(0));
        entity.setMaterialName("合计");
        int serialNumber = 0;
        for (MethylAlcoholListResult item : list) {
            serialNumber++;
            entity.setSerialNumber(serialNumber);
            // 格式化部分字段
            if (item.getWeighbridgeWeight() == null) item.setWeighbridgeWeight(new BigDecimal(0));
            if (item.getSettlementPrice() == null) item.setSettlementPrice(new BigDecimal(0));
            if (item.getSettlementPriceNo() == null) item.setSettlementPriceNo(new BigDecimal(0));
            if (item.getSettlementPriceSum() == null) item.setSettlementPriceSum(new BigDecimal(0));
            if (item.getSettlementPriceSumNo() == null) item.setSettlementPriceSumNo(new BigDecimal(0));
            // 计算合计
            entity.setWeighbridgeWeight(entity.getWeighbridgeWeight().add(item.getWeighbridgeWeight()));
            entity.setSettlementPriceSum(entity.getSettlementPriceSum().add(item.getSettlementPriceSum()));
            entity.setSettlementPriceSumNo(entity.getSettlementPriceSumNo().add(item.getSettlementPriceSumNo()));
        }
        list.add(entity);
        return list;
    }

    // 氢氧化钾
    @Override
    public List<Finance9List3Result> list5(FinanceList3Param param) {
        List<Finance9List3Result> results = new ArrayList<>();
        List<Finance9List3Bo> list = financeMapper.list3(param);
        // 合计
        Finance9List3Result total = new Finance9List3Result();
        total.setNetWeight(new BigDecimal(0));
        total.setWeighbridgeWeight(new BigDecimal(0));
        total.setVehCount(0);
        total.setSettlementPriceSum(new BigDecimal(0));
        total.setSettlementPriceSumNo(new BigDecimal(0));
        total.setCompanyName("合计");
        int serialNumber = 0;
        for (Finance9List3Bo bo : list) {
            serialNumber++;
            // 处理数据计算
            Finance9List3Result item = CglibUtil.copy(bo, Finance9List3Result.class);
            // 用于计算的数量
            BigDecimal quantity = bo.getSettlementMethod() == 2 ? bo.getNetWeight() : bo.getWeighbridgeWeight();
            BigDecimal settlementPriceSum = bo.getSettlementPrice().multiply(quantity);
            BigDecimal settlementPriceNo = FinanceUtil.computeNoTax(bo.getSettlementPrice(), bo.getTaxRate());
            BigDecimal settlementPriceSumNo = settlementPriceNo.multiply(quantity);
            item.setSettlementPriceSum(settlementPriceSum);
            item.setSettlementPriceNo(settlementPriceNo);
            item.setSettlementPriceSumNo(settlementPriceSumNo);
            item.setSerialNumber(serialNumber);
            item.setCarNumber(bo.getCarNumber());
            results.add(item);
            // 计算合计
            total.setNetWeight(total.getNetWeight().add(item.getNetWeight()));
            total.setWeighbridgeWeight(total.getWeighbridgeWeight().add(item.getWeighbridgeWeight()));
            total.setVehCount(total.getVehCount() + item.getVehCount());
            total.setSettlementPriceSum(total.getSettlementPriceSum().add(item.getSettlementPriceSum()));
            total.setSettlementPriceSumNo(total.getSettlementPriceSumNo().add(item.getSettlementPriceSumNo()));
        }
//        results.add(total);
        return results;
    }

    // 硫酸
    @Override
    public List<FinanceList4Result> list6(FinanceList3Param param) {
        List<FinanceList4Result> list = financeMapper.list4(param);
        FinanceList4Result total = new FinanceList4Result();
        total.setWeighbridgeWeight(new BigDecimal(0));
        total.setSettlementPriceSum(new BigDecimal(0));
        total.setSettlementPriceSumNo(new BigDecimal(0));
        total.setNetWeight(new BigDecimal(0));
        total.setVehCount(0);
        total.setMaterialName("合计");
        int serialNumber = 0;
        for (FinanceList4Result item : list) {
            serialNumber++;
            // 格式化部分字段
            if (item.getWeighbridgeWeight() == null) item.setWeighbridgeWeight(new BigDecimal(0));
            if (item.getSettlementPrice() == null) item.setSettlementPrice(new BigDecimal(0));
            if (item.getSettlementPriceNo() == null) item.setSettlementPriceNo(new BigDecimal(0));
            if (item.getSettlementPriceSum() == null) item.setSettlementPriceSum(new BigDecimal(0));
            if (item.getSettlementPriceSumNo() == null) item.setSettlementPriceSumNo(new BigDecimal(0));
            if (item.getFreight() == null) item.setFreight(new BigDecimal(0));
            if (item.getFreightNo() == null) item.setFreightNo(new BigDecimal(0));
            if (item.getNetWeight() == null) item.setNetWeight(new BigDecimal(0));
            item.setSerialNumber(serialNumber);
            // 计算合计
            total.setNetWeight(total.getNetWeight().add(item.getNetWeight()));
            total.setWeighbridgeWeight(total.getWeighbridgeWeight().add(item.getWeighbridgeWeight()));
            total.setVehCount(total.getVehCount() + item.getVehCount());
            total.setSettlementPriceSum(total.getSettlementPriceSum().add(item.getSettlementPriceSum()));
            total.setSettlementPriceSumNo(total.getSettlementPriceSumNo().add(item.getSettlementPriceSumNo()));
        }
//        list.add(total);
        return list;
    }

    @Override
    public List<Finance9ListDtResult> list6Dt(FinanceList3Param param) {
        return financeMapper.list6Dt(param);
    }

    // 液碱
    @Override
    public List<Finance9List7Result> list7(FinanceList3Param param) {
        List<Finance9List7Result> results = new ArrayList<>();
        List<Finance9List7Bo> list = financeMapper.list5(param);
        Finance9List7Result total = new Finance9List7Result();
        total.setCompanyName("合计");
        total.setNetWeight(new BigDecimal(0));
        total.setWeighbridgeWeight(new BigDecimal(0));
        total.setSettlementPriceSum(new BigDecimal(0));
        total.setSettlementPriceSumNo(new BigDecimal(0));
        int serialNumber = 0;
        for (Finance9List7Bo bo : list) {
            serialNumber++;
            // 净含量%
            BigDecimal netContent = getFieldValue(bo.getResult(), 809);
//      BigDecimal netContent = getWater(bo.getResult(), "氢氧化钠，%");
            if (netContent == null) continue;
            // 用来计算的重量
            BigDecimal temp = bo.getWeighbridgeWeight().multiply(netContent.multiply(new BigDecimal(0.01))).setScale(3, BigDecimal.ROUND_HALF_UP);
//            BigDecimal temp = bo.getWeighbridgeWeight().multiply(netContent.divide(new BigDecimal(100)));
            // 不含税单价
            BigDecimal settlementPriceNo = FinanceUtil.computeNoTax(bo.getSettlementPrice(), bo.getTaxRate()).setScale(2, BigDecimal.ROUND_HALF_UP);
            // 不含税总价
            BigDecimal settlementPriceSumNo = temp.multiply(settlementPriceNo);
            // 含税总价
            BigDecimal settlementPriceSum = temp.multiply(bo.getSettlementPrice());
            Finance9List7Result item = CglibUtil.copy(bo, Finance9List7Result.class);
            item.setSettlementPriceSum(settlementPriceSum);
            item.setSettlementPriceSumNo(settlementPriceSumNo);
            item.setNetContent(netContent);
            item.setCarNumber(bo.getCarNumber());
            item.setZeBai(bo.getWeighbridgeWeight().multiply(netContent.multiply(new BigDecimal(0.01))));
//            item.setZeBai(bo.getWeighbridgeWeight().multiply(netContent.multiply(new BigDecimal(0.01))).setScale(3, BigDecimal.ROUND_HALF_UP));
            item.setSerialNumber(serialNumber);
            item.setSettlementPriceNo(settlementPriceNo);
            results.add(item);
            // 计算合计
            total.setNetWeight(total.getNetWeight().add(item.getNetWeight()));
            total.setWeighbridgeWeight(total.getWeighbridgeWeight().add(item.getWeighbridgeWeight()));
            total.setSettlementPriceSum(total.getSettlementPriceSum().add(item.getSettlementPriceSum()));
            total.setSettlementPriceSumNo(total.getSettlementPriceSumNo().add(item.getSettlementPriceSumNo()));
        }
//        results.add(total);
        return results;
    }

    // 聚合硫酸铁
    @Override
    public List<Finance9List9Result> list8(FinanceList3Param param) {
        List<Finance9List9Result> list = financeMapper.list6(param);
        Finance9List9Result entity = new Finance9List9Result();
        entity.setWeighbridgeWeight(new BigDecimal(0));
        entity.setSettlementPriceSum(new BigDecimal(0));
        entity.setSettlementPriceSumNo(new BigDecimal(0));
        entity.setVehCount(0);
        entity.setNetWeight(new BigDecimal(0));
        entity.setCompanyName("合计");
        int serialNumber = 0;
        for (Finance9List9Result item : list) {
            serialNumber++;
            // 格式化部分字段
            if (item.getWeighbridgeWeight() == null) item.setWeighbridgeWeight(new BigDecimal(0));
            if (item.getSettlementPrice() == null) item.setSettlementPrice(new BigDecimal(0));
            if (item.getSettlementPriceNo() == null) item.setSettlementPriceNo(new BigDecimal(0));
            if (item.getSettlementPriceSum() == null) item.setSettlementPriceSum(new BigDecimal(0));
            if (item.getSettlementPriceSumNo() == null) item.setSettlementPriceSumNo(new BigDecimal(0));
            // 计算合计
            entity.setWeighbridgeWeight(entity.getWeighbridgeWeight().add(item.getWeighbridgeWeight()));
            entity.setSettlementPriceSum(entity.getSettlementPriceSum().add(item.getSettlementPriceSum()));
            entity.setSettlementPriceSumNo(entity.getSettlementPriceSumNo().add(item.getSettlementPriceSumNo()));
            entity.setVehCount(entity.getVehCount() + item.getVehCount());
            entity.setNetWeight(entity.getNetWeight().add(item.getNetWeight()));
            item.setSerialNumber(serialNumber);
        }
//        list.add(entity);
        return list;
    }

    @Override
    public List<Finance9ListDtResult> list8Dt(FinanceList3Param param) {
        return financeMapper.list8Dt(param);
    }

    // 焦油数据处理
    @Override
    public List<FinanceList7Result> list9(Finance3CbParam param) {
        // 处理数据
        List<Finance3CbBo> list = financeMapper.list7(param);
        // 新数据集合
        List<FinanceList7Result> results = new ArrayList<>();
        // 小计
        FinanceList7Result subtotal = new FinanceList7Result();
        subtotal.setPlateNumber("小计");
        subtotal.setWeighbridgeWeight(new BigDecimal(0));
        subtotal.setNetWeight(new BigDecimal(0));
        subtotal.setMoney(new BigDecimal(0));
        subtotal.setWithhold(new BigDecimal(0));
        subtotal.setSumWithhold(new BigDecimal(0));
        subtotal.setIncidentals(new BigDecimal(0));
        subtotal.setMoneySum(new BigDecimal(0));
        // 合计
        FinanceList7Result total = new FinanceList7Result();
        total.setPlateNumber("合计");
        total.setWeighbridgeWeight(new BigDecimal(0));
        total.setNetWeight(new BigDecimal(0));
        total.setMoney(new BigDecimal(0));
        total.setWithhold(new BigDecimal(0));
        total.setSumWithhold(new BigDecimal(0));
        total.setIncidentals(new BigDecimal(0));
        total.setMoneySum(new BigDecimal(0));
        String contract = null;
        if (list.size() > 0) contract = list.get(0).getContractNo();
        // 计算数据剩余值
        for (Finance3CbBo bo : list) {
            FinanceList7Result item = CglibUtil.copy(bo, FinanceList7Result.class);
            // 水分
            BigDecimal bigDecimal1 = getWater(bo.getResult());
            item.setWater(bigDecimal1);
//            if (bigDecimal1 == null) continue;
            // 水分扣重
//            if (bigDecimal1.compareTo(new BigDecimal(4)) == 1) {
//                BigDecimal left = new BigDecimal(100).subtract(bigDecimal1);
//                BigDecimal right = new BigDecimal(100).subtract(new BigDecimal(4));
//                // 实物量-（实物量*(1-实际水分)/(1-实际水分)）  水份扣重
//                if (right.compareTo(new BigDecimal(0)) != 0) {
//                    item.setBearing(item.getWaterWithhold().subtract(item.getWeighbridgeWeight().multiply(left).divide(right, 3, BigDecimal.ROUND_DOWN)));
//                }
//            }
            // 水分扣重
            item.setBearing(bo.getMoistureDeduction());
            // 水份扣款
            item.setWaterWithhold(bo.getMoistureDeduction().multiply(item.getFreight()));
            // 磅差吨数
            item.setTunnage(bo.getPoundDifference());
            // 磅差扣款
            BigDecimal bigDecimal = bo.getPoundDifference();
            // 如果有水分扣重，磅差需再减扣重
//            if (item.getBearing() != null && item.getBearing().compareTo(new BigDecimal(0)) == 1) {
//                bigDecimal.subtract(item.getBearing());
//            }
            // 运费扣款
            item.setFreightWithhold(item.getWaterWithhold().add(bigDecimal));
            // 计算磅差扣款(磅差扣款=磅差吨数*运费单价)
            if (bigDecimal.compareTo(new BigDecimal(0)) == 1) {
                item.setWithhold(bigDecimal.multiply(item.getFreight()));
            }
            // 其他扣款(其他扣款*实收吨数)
            item.setOtherWithhold(item.getOtherWithhold().multiply(item.getWeighbridgeWeight()));
            // 合计扣款(磅差扣款+运费扣款+其他扣款)
            BigDecimal bigDecimal2 = new BigDecimal(0);
            // 累加磅差扣款
            if (item.getWithhold() != null && item.getWithhold().compareTo(new BigDecimal(0)) == 1) {
                bigDecimal2 = bigDecimal2.add(item.getWithhold());
            }
            // 累加水分扣款
            if (item.getWaterWithhold() != null && item.getWaterWithhold().compareTo(new BigDecimal(0)) == 1) {
                bigDecimal2 = bigDecimal2.add(item.getWaterWithhold());
            }
            // 累加运费扣款
            if (item.getFreightWithhold() != null && item.getFreightWithhold().compareTo(new BigDecimal(0)) == 1) {
                bigDecimal2 = bigDecimal2.add(item.getFreightWithhold());
            }
            // 累加其他扣款
            if (item.getOtherWithhold() != null && item.getOtherWithhold().compareTo(new BigDecimal(0)) == 1) {
                bigDecimal2 = bigDecimal2.add(item.getOtherWithhold());
            }
            item.setSumWithhold(bigDecimal2);
            // 运杂费
            BigDecimal bigDecimal3 = item.getWeighbridgeWeight().multiply(item.getFreight()).subtract(item.getSumWithhold());
//            if (bigDecimal2.compareTo(new BigDecimal(0)) == 1) {
//                bigDecimal3 = bigDecimal3.subtract(bigDecimal2);
//            }
            item.setIncidentals(bigDecimal3);
            // 运费扣款
            item.setFreightWithhold(item.getWaterWithhold().add(bigDecimal));
            // 总金额
//            item.setMoneySum(item.getMoney().add(item.getIncidentals()));
            // 将处理后的数据填入返回集合
            results.add(item);
            // 保存小计数据，计入合计，重置小计对象
            if (!contract.equals(item.getContractNo())) {
                // 添加小计
                results.add(CglibUtil.copy(subtotal, FinanceList7Result.class));
                // 计算合计
                total.setNetWeight(total.getNetWeight().add(subtotal.getNetWeight()));
                total.setWeighbridgeWeight(total.getWeighbridgeWeight().add(subtotal.getWeighbridgeWeight()));
                total.setMoney(total.getMoney().add(subtotal.getMoney()));
                total.setWithhold(total.getWithhold().add(subtotal.getWithhold()));
                total.setSumWithhold(total.getSumWithhold().add(subtotal.getSumWithhold()));
                total.setIncidentals(total.getIncidentals().add(subtotal.getIncidentals()));
                total.setMoneySum(total.getMoneySum().add(subtotal.getMoneySum()));
                // 更改判断合同号
                contract = item.getContractNo();
                // 清空小计
                subtotal.setPlateNumber("小计");
                subtotal.setNetWeight(new BigDecimal(0));
                subtotal.setWeighbridgeWeight(new BigDecimal(0));
                subtotal.setMoney(new BigDecimal(0));
                subtotal.setWithhold(new BigDecimal(0));
                subtotal.setSumWithhold(new BigDecimal(0));
                subtotal.setIncidentals(new BigDecimal(0));
                subtotal.setMoneySum(new BigDecimal(0));
            }
            // 统计小计
            // 原发数量
            if (item.getNetWeight() != null && item.getNetWeight().compareTo(new BigDecimal(0)) == 1) {
                subtotal.setNetWeight(subtotal.getNetWeight().add(item.getNetWeight()));
            }
            // 实收数量
            if (item.getWeighbridgeWeight() != null && item.getWeighbridgeWeight().compareTo(new BigDecimal(0)) == 1) {
                subtotal.setWeighbridgeWeight(subtotal.getWeighbridgeWeight().add(item.getWeighbridgeWeight()));
            }
            item.setMoney(item.getWeighbridgeWeight().multiply(item.getSettlementPrice()));
            // 金额
            if (item.getMoney() != null && item.getMoney().compareTo(new BigDecimal(0)) == 1) {
                subtotal.setMoney(subtotal.getMoney().add(item.getMoney()));
            }
            // 总金额
            item.setMoneySum(item.getMoney().add(item.getIncidentals()));
            // 扣款
            if (item.getWithhold() != null && item.getWithhold().compareTo(new BigDecimal(0)) == 1) {
                subtotal.setWithhold(subtotal.getWithhold().add(item.getWithhold()));
            }
            // 合计扣款
            if (item.getSumWithhold() != null && item.getSumWithhold().compareTo(new BigDecimal(0)) == 1) {
                subtotal.setSumWithhold(subtotal.getSumWithhold().add(item.getSumWithhold()));
            }
            // 运杂费
            if (item.getIncidentals() != null && item.getIncidentals().compareTo(new BigDecimal(0)) == 1) {
                subtotal.setIncidentals(subtotal.getIncidentals().add(item.getIncidentals()));
            }
            // 总金额
            if (item.getMoneySum() != null && item.getMoneySum().compareTo(new BigDecimal(0)) == 1) {
                subtotal.setMoneySum(subtotal.getMoneySum().add(item.getMoneySum()));
            }
        }
        // 添加小计
//        results.add(CglibUtil.copy(subtotal, FinanceList7Result.class));
        // 计算合计
        total.setNetWeight(total.getNetWeight().add(subtotal.getNetWeight()));
        total.setWeighbridgeWeight(total.getWeighbridgeWeight().add(subtotal.getWeighbridgeWeight()));
        total.setMoney(total.getMoney().add(subtotal.getMoney()));
        total.setWithhold(total.getWithhold().add(subtotal.getWithhold()));
        total.setSumWithhold(total.getSumWithhold().add(subtotal.getSumWithhold()));
        total.setIncidentals(total.getIncidentals().add(subtotal.getIncidentals()));
        total.setMoneySum(total.getMoneySum().add(subtotal.getMoneySum()));
        // 总计
        results.add(total);
        return results;
    }

    // 粗笨，数据处理
    @Override
    public List<Finance3CbResult> list10(Finance3CbParam param) {
        // 原始数据
        List<Finance3CbBo> list = financeMapper.list8(param);
        // 最终返回数据
        List<Finance3CbResult> results = new ArrayList<>();
        // 小计
        Finance3CbResult subtotal = new Finance3CbResult();
        subtotal.setPlateNumber("小计");
        subtotal.setNetWeight(new BigDecimal(0));
        subtotal.setWeighbridgeWeight(new BigDecimal(0));
        subtotal.setMoney(new BigDecimal(0));
        subtotal.setWithhold(new BigDecimal(0));
        subtotal.setSumWithhold(new BigDecimal(0));
        subtotal.setIncidentals(new BigDecimal(0));
        subtotal.setMoneySum(new BigDecimal(0));
        // 合计
        Finance3CbResult total = new Finance3CbResult();
        total.setPlateNumber("合计");
        total.setNetWeight(new BigDecimal(0));
        total.setWeighbridgeWeight(new BigDecimal(0));
        total.setMoney(new BigDecimal(0));
        total.setWithhold(new BigDecimal(0));
        total.setSumWithhold(new BigDecimal(0));
        total.setIncidentals(new BigDecimal(0));
        total.setMoneySum(new BigDecimal(0));
        // 合同号
        String settlementPrice = list.size() > 0 ? list.get(0).getSettlementPrice().toString() : "";
        // 计算数值
        for (Finance3CbBo bo : list) {
            Finance3CbResult item = CglibUtil.copy(bo, Finance3CbResult.class);
            // 计算数据其他字段
            // 水分
//            BigDecimal bigDecimal1 = getWater(bo.getResult());
//            if (bigDecimal1 == null) continue;
            // 水分扣重 实物-（实物*(1000000-实际水分)/990000）
//            if (bigDecimal1.compareTo(new BigDecimal(1000)) == 1) {
//                // 1000000-实际水分
//                BigDecimal left = new BigDecimal(1000000).subtract(bigDecimal1);
//                // 扣重 实物-(实物*left/990000)
//                item.setBearing(bo.getWeighbridgeWeight().subtract(bo.getWeighbridgeWeight().multiply(left).divide(new BigDecimal(990000), 3, BigDecimal.ROUND_DOWN)));
//                // 运费扣款
//                item.setFreightWithhold(item.getBearing().multiply(item.getSettlementPrice()));
//            }
            // 磅差吨数
            item.setTunnage(bo.getPoundDifference());
//            item.setTunnage(bo.getNetWeight().subtract(bo.getWeighbridgeWeight()));
            // 磅差扣款
            BigDecimal bigDecimal = bo.getPoundDifference();
            // 如果有水分扣重，磅差需再减扣重
//            if (item.getBearing() != null && item.getBearing().compareTo(new BigDecimal(0)) == 1) {
//                bigDecimal.subtract(item.getBearing());
//            }
            // 计算磅差扣款
            if (bigDecimal.compareTo(new BigDecimal(0)) == 1) {
                item.setWithhold(bigDecimal.multiply(item.getSettlementPrice()));
            }
            // 其他扣款(其他扣款*实收吨数)
            item.setOtherWithhold(item.getOtherWithhold().multiply(item.getWeighbridgeWeight()));
            // 合计扣款
            BigDecimal bigDecimal2 = new BigDecimal(0);
            // 累加磅差扣款
            if (item.getWithhold() != null && item.getWithhold().compareTo(new BigDecimal(0)) == 1) {
                bigDecimal2 = bigDecimal2.add(item.getWithhold());
            }
            // 累加水分扣款
//            if (item.getWaterWithhold() != null && item.getWaterWithhold().compareTo(new BigDecimal(0)) == 1) {
//                bigDecimal2 = bigDecimal2.add(item.getWaterWithhold());
//            }
            // 累加运费扣款
            if (item.getFreightWithhold() != null && item.getFreightWithhold().compareTo(new BigDecimal(0)) == 1) {
                bigDecimal2 = bigDecimal2.add(item.getFreightWithhold());
            }
            // 累加其他扣款
            if (item.getOtherWithhold() != null && item.getOtherWithhold().compareTo(new BigDecimal(0)) == 1) {
                bigDecimal2 = bigDecimal2.add(item.getOtherWithhold());
            }
            item.setSumWithhold(bigDecimal2);
            // 运杂费
            BigDecimal bigDecimal3 = item.getWeighbridgeWeight().multiply(item.getFreight());
            if (bigDecimal2.compareTo(new BigDecimal(0)) == 1) {
                bigDecimal3 = bigDecimal3.subtract(bigDecimal2);
            }
            item.setIncidentals(bigDecimal3);
            // 金额
            item.setMoney(item.getWeighbridgeWeight().multiply(item.getSettlementPrice()));
            // 总金额
            item.setMoneySum(item.getMoney().add(item.getIncidentals()));
            // 将处理后的数据填入返回集合
            results.add(item);
            // 统计合计
            if (!settlementPrice.equals(item.getSettlementPrice().toString())) {
                // 添加小计
                results.add(CglibUtil.copy(subtotal, Finance3CbResult.class));
                // 计算合计
                total.setNetWeight(total.getNetWeight().add(subtotal.getNetWeight()));
                total.setWeighbridgeWeight(total.getWeighbridgeWeight().add(subtotal.getWeighbridgeWeight()));
                total.setMoney(total.getMoney().add(subtotal.getMoney()));
                total.setWithhold(total.getWithhold().add(subtotal.getWithhold()));
                total.setSumWithhold(total.getSumWithhold().add(subtotal.getSumWithhold()));
                total.setIncidentals(total.getIncidentals().add(subtotal.getIncidentals()));
                total.setMoneySum(total.getMoneySum().add(subtotal.getMoneySum()));
                // 更改判断合同号
                settlementPrice = item.getSettlementPrice().toString();
                // 清空小计
                subtotal.setPlateNumber("小计");
                subtotal.setNetWeight(new BigDecimal(0));
                subtotal.setWeighbridgeWeight(new BigDecimal(0));
                subtotal.setMoney(new BigDecimal(0));
                subtotal.setWithhold(new BigDecimal(0));
                subtotal.setSumWithhold(new BigDecimal(0));
                subtotal.setIncidentals(new BigDecimal(0));
                subtotal.setMoneySum(new BigDecimal(0));
            }
            // 统计小计
            // 原发数量
            if (item.getNetWeight() != null && item.getNetWeight().compareTo(new BigDecimal(0)) == 1) {
                subtotal.setNetWeight(subtotal.getNetWeight().add(item.getNetWeight()));
            }
            // 实收数量
            if (item.getWeighbridgeWeight() != null && item.getWeighbridgeWeight().compareTo(new BigDecimal(0)) == 1) {
                subtotal.setWeighbridgeWeight(subtotal.getWeighbridgeWeight().add(item.getWeighbridgeWeight()));
            }
            // 金额
            if (item.getMoney() != null && item.getMoney().compareTo(new BigDecimal(0)) == 1) {
                subtotal.setMoney(subtotal.getMoney().add(item.getMoney()));
            }
            // 扣款
            if (item.getWithhold() != null && item.getWithhold().compareTo(new BigDecimal(0)) == 1) {
                subtotal.setWithhold(subtotal.getWithhold().add(item.getWithhold()));
            }
            // 合计扣款
            if (item.getSumWithhold() != null && item.getSumWithhold().compareTo(new BigDecimal(0)) == 1) {
                subtotal.setSumWithhold(subtotal.getSumWithhold().add(item.getSumWithhold()));
            }
            // 运杂费
            if (item.getIncidentals() != null && item.getIncidentals().compareTo(new BigDecimal(0)) == 1) {
                subtotal.setIncidentals(subtotal.getIncidentals().add(item.getIncidentals()));
            }
            // 总金额
            if (item.getMoneySum() != null && item.getMoneySum().compareTo(new BigDecimal(0)) == 1) {
                subtotal.setMoneySum(subtotal.getMoneySum().add(item.getMoneySum()));
            }
        }
        // 添加合计
        results.add(total);
        return results;
    }

    /**
     * 焦油厂销售-按产品分类报表 数据处理
     */
    @Override
    public List<Finance4ListResult> list12(Finance4ListParam param) {
        List<Finance4ListResult> list = financeMapper.list9(param);
        // 合计
        Finance4ListResult total = new Finance4ListResult();
        total.setMaterialName("合计");
        total.setMoney(new BigDecimal(0));
        total.setAssembleMoney(new BigDecimal(0));
        total.setSettlementPrice(new BigDecimal(0));
        total.setMoneySum(new BigDecimal(0));
        total.setWeighbridgeWeight(new BigDecimal(0));
        for (Finance4ListResult item : list) {
            item.setSettlementPrice(item.getSettlementPrice().setScale(2, BigDecimal.ROUND_DOWN));
            total.setMoney(total.getMoney().add(item.getMoney()));
            total.setWeighbridgeWeight(total.getWeighbridgeWeight().add(item.getWeighbridgeWeight()));
            total.setSettlementPrice(total.getSettlementPrice().add(item.getSettlementPrice()));
            total.setMoneySum(total.getMoneySum().add(item.getMoneySum()));
            total.setAssembleMoney(total.getAssembleMoney().add(item.getAssembleMoney()));
        }
        // 计算单价
        if (total.getWeighbridgeWeight().compareTo(new BigDecimal(0)) != 0) {
            BigDecimal bigDecimal = total.getMoney().divide(total.getWeighbridgeWeight(), 2, BigDecimal.ROUND_DOWN);
            total.setSettlementPrice(bigDecimal);
        }
        list.add(total);
        return list;
    }

    /**
     * 笨精制销售-按产品分类报表 数据处理
     */
    @Override
    public List<Finance5ListResult> list13(Finance5ListParam param) {
        List<Finance5ListResult> list = financeMapper.list10(param);
        // 合计
        Finance5ListResult total = new Finance5ListResult();
        total.setMaterialName("合计");
        total.setMoney(new BigDecimal(0));
        total.setAssembleMoney(new BigDecimal(0));
        total.setSettlementPrice(new BigDecimal(0));
        total.setMoneySum(new BigDecimal(0));
        total.setWeighbridgeWeight(new BigDecimal(0));
        for (Finance5ListResult item : list) {
            item.setSettlementPrice(item.getSettlementPrice().setScale(2, BigDecimal.ROUND_DOWN));
            total.setMoney(total.getMoney().add(item.getMoney()));
            total.setWeighbridgeWeight(total.getWeighbridgeWeight().add(item.getWeighbridgeWeight()));
            total.setMoneySum(total.getMoneySum().add(item.getMoneySum()));
            total.setAssembleMoney(total.getAssembleMoney().add(item.getAssembleMoney()));
        }
        if (total.getWeighbridgeWeight().compareTo(new BigDecimal(0)) != 0) {
            BigDecimal bigDecimal = total.getMoney().divide(total.getWeighbridgeWeight(), 2, BigDecimal.ROUND_DOWN);
            total.setSettlementPrice(bigDecimal);
        }
        list.add(total);
        return list;
    }

    /**
     * 焦油厂销售/笨精制销售-客户销售报表  数据处理
     */
    @Override
    public List<Finance4KhXsResult> list14(Finance4ListParam param, Integer type) {
        List<Finance4KhXsResult> list;
        List<Finance4KhXsResult> results = new ArrayList<>();
        if (type == 0) {
            list = financeMapper.list11(param);
        } else {
            list = financeMapper.list12(param);
        }
        // 合计
        Finance4KhXsResult total = new Finance4KhXsResult();
//    total.setMaterialName("合计");
        total.setCompanyName("合计");
        total.setMoney(new BigDecimal(0));
        total.setAssembleMoney(new BigDecimal(0));
        total.setSettlementPrice(new BigDecimal(0));
        total.setMoneySum(new BigDecimal(0));
        total.setWeighbridgeWeight(new BigDecimal(0));
        // 小计
        Finance4KhXsResult subtotal = new Finance4KhXsResult();
//    subtotal.setMaterialName("小计");
        subtotal.setCompanyName("小计");
        subtotal.setMoney(new BigDecimal(0));
        subtotal.setAssembleMoney(new BigDecimal(0));
        subtotal.setSettlementPrice(new BigDecimal(0));
        subtotal.setMoneySum(new BigDecimal(0));
        subtotal.setWeighbridgeWeight(new BigDecimal(0));
        String companyName = list.size() > 0 ? list.get(0).getCompanyName() : "";
        for (Finance4KhXsResult item : list) {
            if (!item.getCompanyName().equals(companyName)) {
                // 更新判断字段
                companyName = item.getCompanyName();
                // 计算小计的单价（金额/数量）
                if (subtotal.getWeighbridgeWeight().compareTo(new BigDecimal(0)) != 0) {
                    subtotal.setSettlementPrice(subtotal.getMoney().divide(subtotal.getWeighbridgeWeight(), 2, BigDecimal.ROUND_DOWN));
                }
                results.add(CglibUtil.copy(subtotal, Finance4KhXsResult.class));
                // 清空小计
                subtotal.setMoney(new BigDecimal(0));
                subtotal.setAssembleMoney(new BigDecimal(0));
                subtotal.setSettlementPrice(new BigDecimal(0));
                subtotal.setMoneySum(new BigDecimal(0));
                subtotal.setWeighbridgeWeight(new BigDecimal(0));
            }
            // 正常添加数据
            results.add(item);
            // 统计小计
            subtotal.setMoney(subtotal.getMoney().add(item.getMoney()));
            subtotal.setWeighbridgeWeight(subtotal.getWeighbridgeWeight().add(item.getWeighbridgeWeight()));
            subtotal.setSettlementPrice(subtotal.getSettlementPrice().add(item.getSettlementPrice()));
            subtotal.setMoneySum(subtotal.getMoneySum().add(item.getMoneySum()));
            subtotal.setAssembleMoney(subtotal.getAssembleMoney().add(item.getAssembleMoney()));
            // 统计合计
            total.setMoney(total.getMoney().add(item.getMoney()));
            total.setWeighbridgeWeight(total.getWeighbridgeWeight().add(item.getWeighbridgeWeight()));
            total.setSettlementPrice(total.getSettlementPrice().add(item.getSettlementPrice()));
            total.setMoneySum(total.getMoneySum().add(item.getMoneySum()));
            total.setAssembleMoney(total.getAssembleMoney().add(item.getAssembleMoney()));
        }
        results.add(subtotal);
        // 计算合计单价
        if (total.getWeighbridgeWeight().compareTo(new BigDecimal(0)) != 0) {
            total.setSettlementPrice(total.getMoney().divide(total.getWeighbridgeWeight(), 2, BigDecimal.ROUND_DOWN));
        }
        results.add(total);
        return results;
    }

    /**
     * 焦油厂销售/笨精制销售-产品销售报表  数据处理
     */
    @Override
    public List<Finance4KhXsResult> list15(Finance4ListParam param, Integer type) {
        List<Finance4KhXsResult> list;
        List<Finance4KhXsResult> results = new ArrayList<>();
        if (type == 0) {
            list = financeMapper.list13(param);
        } else {
            list = financeMapper.list14(param);
        }
        // 合计
        Finance4KhXsResult total = new Finance4KhXsResult();
//    total.setCompanyName("合计");
        total.setMaterialName("合计");
        total.setMoney(new BigDecimal(0));
        total.setAssembleMoney(new BigDecimal(0));
        total.setSettlementPrice(new BigDecimal(0));
        total.setMoneySum(new BigDecimal(0));
        total.setWeighbridgeWeight(new BigDecimal(0));
        total.setAdvance(new BigDecimal(0));
        total.setSpecial(new BigDecimal(0));
        total.setPack(new BigDecimal(0));
        total.setOther(new BigDecimal(0));
        // 小计
        Finance4KhXsResult subtotal = new Finance4KhXsResult();
//    subtotal.setCompanyName("小计");
        subtotal.setMaterialName("小计");
        subtotal.setMoney(new BigDecimal(0));
        subtotal.setAssembleMoney(new BigDecimal(0));
        subtotal.setSettlementPrice(new BigDecimal(0));
        subtotal.setMoneySum(new BigDecimal(0));
        subtotal.setWeighbridgeWeight(new BigDecimal(0));
        subtotal.setAdvance(new BigDecimal(0));
        subtotal.setSpecial(new BigDecimal(0));
        subtotal.setPack(new BigDecimal(0));
        subtotal.setOther(new BigDecimal(0));
        String materialName = list.size() > 0 ? list.get(0).getMaterialName() : "";
        for (Finance4KhXsResult item : list) {
            // 保留小数位
            item.setSettlementPrice(item.getSettlementPrice().setScale(2, BigDecimal.ROUND_DOWN));
            if (!item.getMaterialName().equals(materialName)) {
                // 更新判断字段
                materialName = item.getMaterialName();
                // 计算小计的单价（金额/数量）
                if (subtotal.getWeighbridgeWeight().compareTo(new BigDecimal(0)) != 0) {
                    subtotal.setSettlementPrice(subtotal.getMoney().divide(subtotal.getWeighbridgeWeight(), 2, BigDecimal.ROUND_DOWN));
                }
                // 添加小计
                results.add(CglibUtil.copy(subtotal, Finance4KhXsResult.class));
                // 清空小计
                subtotal.setMoney(new BigDecimal(0));
                subtotal.setAssembleMoney(new BigDecimal(0));
                subtotal.setSettlementPrice(new BigDecimal(0));
                subtotal.setMoneySum(new BigDecimal(0));
                subtotal.setWeighbridgeWeight(new BigDecimal(0));
            }
            // 正常添加数据
            results.add(item);
            // 统计小计
            subtotal.setMoney(subtotal.getMoney().add(item.getMoney()));
            subtotal.setWeighbridgeWeight(subtotal.getWeighbridgeWeight().add(item.getWeighbridgeWeight()));
            subtotal.setMoneySum(subtotal.getMoneySum().add(item.getMoneySum()));
            subtotal.setAssembleMoney(subtotal.getAssembleMoney().add(item.getAssembleMoney()));
            subtotal.setAdvance(subtotal.getAdvance().add(item.getAdvance()));
            subtotal.setSpecial(subtotal.getSpecial().add(item.getSpecial()));
            subtotal.setPack(subtotal.getPack().add(item.getPack()));
            subtotal.setOther(subtotal.getOther().add(item.getOther()));
            // 统计合计
            total.setMoney(total.getMoney().add(item.getMoney()));
            total.setWeighbridgeWeight(total.getWeighbridgeWeight().add(item.getWeighbridgeWeight()));
            total.setMoneySum(total.getMoneySum().add(item.getMoneySum()));
            total.setAssembleMoney(total.getAssembleMoney().add(item.getAssembleMoney()));
            total.setAdvance(total.getAdvance().add(item.getAdvance()));
            total.setSpecial(total.getSpecial().add(item.getSpecial()));
            total.setPack(total.getPack().add(item.getPack()));
            total.setOther(total.getOther().add(item.getOther()));
        }
        // 最后一次循环漏掉的小计存入集合
        results.add(subtotal);
        // 计算合计单价
        if (total.getWeighbridgeWeight().compareTo(new BigDecimal(0)) != 0) {
            total.setSettlementPrice(total.getMoney().divide(total.getWeighbridgeWeight(), 2, BigDecimal.ROUND_DOWN));
        }
        // 存入合计
        results.add(total);
        return results;
    }

    /**
     * 焦油厂销售/笨精制销售-客户明细销售报表 数据处理
     */
    public List<Finance4KhMxResult> list16(Finance4ListParam param, Integer type) {
        List<Finance4KhMxResult> list;
        List<Finance4KhMxResult> results = new ArrayList<>();
        if (type == 0) {
            list = financeMapper.list15(param);
            // 按公司分类
            Map<String, List<Finance4KhMxResult>> collect1 = list.stream().collect(
                    Collectors.groupingBy(Finance4KhMxResult::getCompanyName, Collectors.toList()));
            for (String str : collect1.keySet()) {
                Finance4KhMxResult subtotal = new Finance4KhMxResult();
                subtotal.setCompanyName("合计");
                subtotal.setMoney(new BigDecimal(0));
                subtotal.setAssembleMoney(new BigDecimal(0));
                subtotal.setSettlementPrice(new BigDecimal(0));
                subtotal.setMoneySum(new BigDecimal(0));
                subtotal.setWeighbridgeWeight(new BigDecimal(0));
                subtotal.setAdvance(new BigDecimal(0));
                subtotal.setSpecial(new BigDecimal(0));
                subtotal.setPack(new BigDecimal(0));
                subtotal.setOther(new BigDecimal(0));
                List<Finance4KhMxResult> collect2 = collect1.get(str).stream()
                        .sorted(Comparator.comparing(Finance4KhMxResult::getMaterialName).thenComparing(Finance4KhMxResult::getFactoryOutTime))
                        .collect(Collectors.toList());
                for (Finance4KhMxResult finance4KhMxResult : collect2) {

                    if (subtotal.getWeighbridgeWeight() == null || subtotal.getWeighbridgeWeight().compareTo(new BigDecimal(0)) == 0) {
                        results.add(finance4KhMxResult);
                    } else {
                        finance4KhMxResult.setCompanyName(null);
                        results.add(finance4KhMxResult);
                    }
                    subtotal.setWeighbridgeWeight(subtotal.getWeighbridgeWeight().add(finance4KhMxResult.getWeighbridgeWeight()));
                    if (finance4KhMxResult.getSettlementPrice() != null && finance4KhMxResult.getSettlementPrice().compareTo(new BigDecimal(0)) != 0) {
                        subtotal.setSettlementPrice(new BigDecimal(0));
                    }
                    subtotal.setMoney(subtotal.getMoney().add(finance4KhMxResult.getMoney()));
                    subtotal.setAdvance(subtotal.getAdvance().add(finance4KhMxResult.getAdvance()));
                    subtotal.setSpecial(subtotal.getSpecial().add(finance4KhMxResult.getSpecial()));
                    subtotal.setPack(subtotal.getPack().add(finance4KhMxResult.getPack()));
                    subtotal.setOther(subtotal.getOther().add(finance4KhMxResult.getOther()));
                    subtotal.setAssembleMoney(subtotal.getAssembleMoney().add(finance4KhMxResult.getAssembleMoney()));
                    subtotal.setMoneySum(subtotal.getMoneySum().add(finance4KhMxResult.getMoneySum()));
                }
                subtotal.setSettlementPrice(subtotal.getMoney().divide(subtotal.getWeighbridgeWeight(), 2, BigDecimal.ROUND_HALF_UP));
                results.add(subtotal);
            }
            return results;
        } else {
            list = financeMapper.list16(param);
        }
        // 合计
        Finance4KhMxResult total = new Finance4KhMxResult();
//    total.setMaterialName("合计");
        total.setCompanyName("合计");
        total.setMoney(new BigDecimal(0));
        total.setAssembleMoney(new BigDecimal(0));
        total.setSettlementPrice(new BigDecimal(0));
        total.setMoneySum(new BigDecimal(0));
        total.setWeighbridgeWeight(new BigDecimal(0));
        total.setAdvance(new BigDecimal(0));
        total.setSpecial(new BigDecimal(0));
        total.setPack(new BigDecimal(0));
        total.setOther(new BigDecimal(0));
        // 小计
        Finance4KhMxResult subtotal = new Finance4KhMxResult();
//    subtotal.setMaterialName("小计");
        subtotal.setCompanyName("小计");
        subtotal.setMoney(new BigDecimal(0));
        subtotal.setAssembleMoney(new BigDecimal(0));
        subtotal.setSettlementPrice(new BigDecimal(0));
        subtotal.setMoneySum(new BigDecimal(0));
        subtotal.setWeighbridgeWeight(new BigDecimal(0));
        subtotal.setAdvance(new BigDecimal(0));
        subtotal.setSpecial(new BigDecimal(0));
        subtotal.setPack(new BigDecimal(0));
        subtotal.setOther(new BigDecimal(0));
        String companyName = list.size() > 0 ? list.get(0).getCompanyName() : "";
        for (Finance4KhMxResult item : list) {
            if (!item.getCompanyName().equals(companyName)) {
                // 更新判断字段
                companyName = item.getCompanyName();
                // 计算小计的单价（金额/数量）
                if (subtotal.getWeighbridgeWeight().compareTo(new BigDecimal(0)) != 0) {
                    subtotal.setSettlementPrice(subtotal.getMoney().divide(subtotal.getWeighbridgeWeight(), 2, BigDecimal.ROUND_DOWN));
                }
                results.add(CglibUtil.copy(subtotal, Finance4KhMxResult.class));
                // 清空小计
                subtotal.setMoney(new BigDecimal(0));
                subtotal.setAssembleMoney(new BigDecimal(0));
                subtotal.setSettlementPrice(new BigDecimal(0));
                subtotal.setMoneySum(new BigDecimal(0));
                subtotal.setWeighbridgeWeight(new BigDecimal(0));
            }
            // 正常添加数据
            results.add(item);
            // 统计小计
            subtotal.setMoney(subtotal.getMoney().add(item.getMoney()));
            subtotal.setWeighbridgeWeight(subtotal.getWeighbridgeWeight().add(item.getWeighbridgeWeight()));
            subtotal.setSettlementPrice(subtotal.getSettlementPrice().add(item.getSettlementPrice()));
            subtotal.setMoneySum(subtotal.getMoneySum().add(item.getMoneySum()));
            subtotal.setAssembleMoney(subtotal.getAssembleMoney().add(item.getAssembleMoney()));
            // 统计合计
            total.setMoney(total.getMoney().add(item.getMoney()));
            total.setWeighbridgeWeight(total.getWeighbridgeWeight().add(item.getWeighbridgeWeight()));
            total.setSettlementPrice(total.getSettlementPrice().add(item.getSettlementPrice()));
            total.setMoneySum(total.getMoneySum().add(item.getMoneySum()));
            total.setAssembleMoney(total.getAssembleMoney().add(item.getAssembleMoney()));
        }
        results.add(subtotal);
        // 计算合计单价
        if (total.getWeighbridgeWeight().compareTo(new BigDecimal(0)) != 0) {
            total.setSettlementPrice(total.getMoney().divide(total.getWeighbridgeWeight(), 2, BigDecimal.ROUND_DOWN));
        }
        results.add(total);
        return results;
    }

    /**
     * 焦油厂销售/笨精制销售-客户开票
     */
    @Override
    public List<Finance4KhKpResult> list17(Finance4ListParam param, Integer type) {
        List<Finance4KhKpResult> list;
        List<Finance4KhKpResult> results = new ArrayList<>();
        if (type == 0) {
//            list = financeMapper.list17(param);
            List<Finance4KhMxResult> list1;
            list1 = financeMapper.list15(param);
            // 按公司分类
            Map<String, List<Finance4KhMxResult>> collect1 = list1.stream().collect(
                    Collectors.groupingBy(Finance4KhMxResult::getCompanyName, Collectors.toList()));
            for (String str : collect1.keySet()) {
                Finance4KhKpResult subtotal = new Finance4KhKpResult();
                subtotal.setCompanyName("合计");
                subtotal.setMoney(new BigDecimal(0));
                subtotal.setAssembleMoney(new BigDecimal(0));
                subtotal.setSettlementPrice(new BigDecimal(0));
                subtotal.setMoneySum(new BigDecimal(0));
                subtotal.setWeighbridgeWeight(new BigDecimal(0));
                // 按公司分类
                Map<String, List<Finance4KhMxResult>> collect2 = collect1.get(str).stream().collect(
                        Collectors.groupingBy(item -> item.getSettlementPrice() + "_" + item.getMaterialName()));
                for (String str1 : collect2.keySet()) {
                    Finance4KhKpResult finance4KhKpResult = new Finance4KhKpResult();
                    finance4KhKpResult.setMoney(new BigDecimal(0));
                    finance4KhKpResult.setAssembleMoney(new BigDecimal(0));
                    finance4KhKpResult.setSettlementPrice(new BigDecimal(0));
                    finance4KhKpResult.setMoneySum(new BigDecimal(0));
                    finance4KhKpResult.setWeighbridgeWeight(new BigDecimal(0));
                    for (int i = 0; i < collect2.get(str1).size(); i++) {
                        finance4KhKpResult.setCompanyName(collect2.get(str1).get(i).getCompanyName());
                        finance4KhKpResult.setMaterialName(collect2.get(str1).get(i).getMaterialName());
                        finance4KhKpResult.setWeighbridgeWeight(finance4KhKpResult.getWeighbridgeWeight().add(collect2.get(str1).get(i).getWeighbridgeWeight()));
                        finance4KhKpResult.setSettlementPrice(finance4KhKpResult.getSettlementPrice().add(collect2.get(str1).get(i).getSettlementPrice()));
                        finance4KhKpResult.setMoney(finance4KhKpResult.getMoney().add(collect2.get(str1).get(i).getMoney()));
                        finance4KhKpResult.setAssembleMoney(finance4KhKpResult.getAssembleMoney().add(collect2.get(str1).get(i).getAssembleMoney()));
                        finance4KhKpResult.setMoneySum(finance4KhKpResult.getMoneySum().add(collect2.get(str1).get(i).getMoneySum()));
                    }
                    if (subtotal.getWeighbridgeWeight() == null || subtotal.getWeighbridgeWeight().compareTo(new BigDecimal(0)) == 0) {
                        results.add(finance4KhKpResult);
                    } else {
                        finance4KhKpResult.setCompanyName(null);
                        results.add(finance4KhKpResult);
                    }
                    subtotal.setWeighbridgeWeight(subtotal.getWeighbridgeWeight().add(finance4KhKpResult.getWeighbridgeWeight()));
                    subtotal.setMoney(subtotal.getMoney().add(finance4KhKpResult.getMoney()));
                    subtotal.setAssembleMoney(subtotal.getAssembleMoney().add(finance4KhKpResult.getAssembleMoney()));
                    subtotal.setMoneySum(subtotal.getMoneySum().add(finance4KhKpResult.getMoneySum()));
                }
                results.add(subtotal);
            }
            return results;
        } else {
            list = financeMapper.list18(param);
        }
        // 合计
        Finance4KhKpResult total = new Finance4KhKpResult();
        total.setCompanyName("合计");
//    total.setMaterialName("合计");
        total.setMoney(new BigDecimal(0));
        total.setAssembleMoney(new BigDecimal(0));
        total.setSettlementPrice(new BigDecimal(0));
        total.setMoneySum(new BigDecimal(0));
        total.setWeighbridgeWeight(new BigDecimal(0));
        // 小计
        Finance4KhKpResult subtotal = new Finance4KhKpResult();
        subtotal.setCompanyName("小计");
//    subtotal.setMaterialName("小计");
        subtotal.setMoney(new BigDecimal(0));
        subtotal.setAssembleMoney(new BigDecimal(0));
        subtotal.setSettlementPrice(new BigDecimal(0));
        subtotal.setMoneySum(new BigDecimal(0));
        subtotal.setWeighbridgeWeight(new BigDecimal(0));
        String companyName = list.size() > 0 ? list.get(0).getCompanyName() : "";
        for (Finance4KhKpResult item : list) {
            if (!item.getCompanyName().equals(companyName)) {
                // 更新判断字段
                companyName = item.getCompanyName();
                // 清空小计
                subtotal.setMoney(new BigDecimal(0));
                subtotal.setAssembleMoney(new BigDecimal(0));
                subtotal.setSettlementPrice(new BigDecimal(0));
                subtotal.setMoneySum(new BigDecimal(0));
                subtotal.setWeighbridgeWeight(new BigDecimal(0));
            }
            // 正常添加数据
            results.add(item);
            // 统计小计
            subtotal.setMoney(subtotal.getMoney().add(item.getMoney()));
            subtotal.setWeighbridgeWeight(subtotal.getWeighbridgeWeight().add(item.getWeighbridgeWeight()));
            subtotal.setSettlementPrice(subtotal.getSettlementPrice().add(item.getSettlementPrice()));
            subtotal.setMoneySum(subtotal.getMoneySum().add(item.getMoneySum()));
            subtotal.setAssembleMoney(subtotal.getAssembleMoney().add(item.getAssembleMoney()));
            // 统计合计
            total.setMoney(total.getMoney().add(item.getMoney()));
            total.setWeighbridgeWeight(total.getWeighbridgeWeight().add(item.getWeighbridgeWeight()));
            total.setSettlementPrice(total.getSettlementPrice().add(item.getSettlementPrice()));
            total.setMoneySum(total.getMoneySum().add(item.getMoneySum()));
            total.setAssembleMoney(total.getAssembleMoney().add(item.getAssembleMoney()));
        }
        results.add(subtotal);
        // 计算合计单价
        if (total.getWeighbridgeWeight().compareTo(new BigDecimal(0)) != 0) {
            total.setSettlementPrice(total.getMoney().divide(total.getWeighbridgeWeight(), 2, BigDecimal.ROUND_DOWN));
        }
        results.add(total);
        return results;
    }

    /**
     * 煤报表数据处理
     */
    @Override
    public List<Finance6ListResult> list18(Finance6ListParam param) {
        List<Finance6ListResult> list = financeMapper.list19(param);
        Finance6ListResult entity = new Finance6ListResult();
        entity.setMaterialName("合计");
        entity.setWeighbridgeWeight(new BigDecimal(0));
        entity.setVehCount(0);
        entity.setQuantity(new BigDecimal(0));
        for (Finance6ListResult item : list) {
            // 计算合计
            entity.setWeighbridgeWeight(entity.getWeighbridgeWeight().add(item.getWeighbridgeWeight()));
            entity.setVehCount(entity.getVehCount() + item.getVehCount());
            entity.setQuantity(entity.getQuantity().add(item.getQuantity()));
            // 抓取质检结果
            String result = item.getResult();
            if (result == null) continue;
            item.setWater(getFieldValue1(result, "全水分 Mt， %"));
            item.setAsh(getFieldValue1(result, "灰分 Ad， %"));
            item.setVolatilize(getFieldValue1(result, "挥发分Vdaf，%"));
            item.setSulfur(getFieldValue1(result, "硫分 St,d，%"));
            item.setColloidalX(getFieldValue1(result, "胶质层收缩度 X，mm"));
            item.setColloidalY(getFieldValue1(result, "最大胶质层厚度 Y，mm"));
            item.setSplice(getFieldValue1(result, "粘结指数 Gʀ.ɪ"));
//            item.setWater(getFieldValue(result, 2382));
//            item.setAsh(getFieldValue(result, 2383));
//            item.setVolatilize(getFieldValue(result, 2384));
//            item.setSulfur(getFieldValue(result, 2385));
//            item.setColloidalX(getFieldValue(result, 2386));
//            item.setColloidalY(getFieldValue(result, 2387));
//            item.setSplice(getFieldValue(result, 2388));
//      item.set
//      item.setAsh(getWater(result, "灰分"));
//      item.setVolatilize(getWater(result, "挥发分"));
//      item.setSulfur(getWater(result, "硫分"));
//      item.setColloidal(getWater(result, "胶质层"));
//      item.setViscosity(getWater(result, "黏度"));
//      item.setPetro(getWater(result, "岩相"));
            item.setExtra(getRemark(item.getExtra()));
            // 扣水和结算数量计算
            BigDecimal water = item.getWater();
            if (water == null) continue;
            item.setWater(water);
            if (water.compareTo(new BigDecimal(8)) != 1) continue;
            // 水分大于8% 进行数据处理 (1-质检水分）/（1-0.08）* 净重
            BigDecimal bigDecimal = new BigDecimal(1).subtract(water.divide(new BigDecimal(100)));
            BigDecimal bigDecimal1 = item.getWeighbridgeWeight().multiply(bigDecimal).divide(new BigDecimal(0.92), 2, BigDecimal.ROUND_DOWN);
            item.setQuantity(bigDecimal1);
            // 清空质检结果
            item.setResult("");
        }
//        list.add(entity);
        return list;
    }

    /**
     * 液氨数据处理
     *
     * @param param
     * @return
     */
    @Override
    public List<ChemicalYaResult> list19(FinanceList3Param param) {
        List<ChemicalYaResult> list = chemicalMapper.ya(param);
        ChemicalYaResult entity = new ChemicalYaResult();
        entity.setCarNumber("合计");
        entity.setNetWeight(new BigDecimal(0));
        entity.setWeighbridgeWeight(new BigDecimal(0));
        entity.setMoney(new BigDecimal(0));
        entity.setMoneySum(new BigDecimal(0));
        int serialNumber = 0;
        for (ChemicalYaResult item : list) {
            serialNumber++;
            // 磅差大于0.06才处理（超出部分扣钱）
            if (item.getTunnage().compareTo(new BigDecimal(0.06)) == 1) {
                // 扣重
                BigDecimal bigDecimal = item.getTunnage().subtract(new BigDecimal(0.06));
                // 扣款
                BigDecimal bigDecimal1 = bigDecimal.multiply(item.getSettlementPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
                item.setWithhold(bigDecimal1);
                // 运费扣款
                item.setAssemble_money(item.getAssemble_money().subtract(bigDecimal1));
                // 总金额扣款
                item.setMoneySum(item.getMoneySum().subtract(bigDecimal1));
            }
            // 格式化部分字符串
            if (item.getNetWeight() == null) item.setNetWeight(new BigDecimal(0));
            if (item.getWeighbridgeWeight() == null) item.setWeighbridgeWeight(new BigDecimal(0));
            if (item.getMoney() == null) item.setMoney(new BigDecimal(0));
            if (item.getMoneySum() == null) item.setMoneySum(new BigDecimal(0));
            item.setSerialNumber(serialNumber);
            // 计算合计
            entity.setNetWeight(entity.getNetWeight().add(item.getNetWeight()));
            entity.setWeighbridgeWeight(entity.getWeighbridgeWeight().add(item.getWeighbridgeWeight()));
            entity.setMoney(entity.getMoney().add(item.getMoney()));
            entity.setMoneySum(entity.getMoneySum().add(item.getMoneySum()));
            entity.setCarNumber(entity.getCarNumber());
            entity.setCompanyName(entity.getCompanyName());
        }
//        list.add(entity);
        return list;
    }

    /**
     * 焦炭数据处理
     */
    @Override
    @Deprecated
    public List<Finance7ListResult> list20(Finance7ListParam param) {
        List<Finance7ListResult> list = financeMapper.list20(param);
        // 数据处理
        for (Finance7ListResult item : list) {
            // 拿质检结果
            item.setWaterResult(getWater(item.getResult()));
            item.setAshResult(getWater(item.getResult(), "灰分"));
            item.setSulfurResult(getWater(item.getResult(), "硫"));
            item.setVolatilizeResult(getWater(item.getResult(), "挥发份"));
            item.setFoamResult(getWater(item.getResult(), "焦沫"));
            item.setM40Result(getWater(item.getResult(), "m40"));
            item.setM10Result(getWater(item.getResult(), "m10"));
            item.setCsrResult(getWater(item.getResult(), "csr"));
            item.setCriResult(getWater(item.getResult(), "cri"));
            // 单价扣奖
            BigDecimal bigDecimal = new BigDecimal(0);
            if (item.getAsh() != null) bigDecimal.add(item.getAsh());
            if (item.getSulfur() != null) bigDecimal.add(item.getSulfur());
            if (item.getVolatilize() != null) bigDecimal.add(item.getVolatilize());
            if (item.getFoam() != null) bigDecimal.add(item.getFoam());
            if (item.getM40() != null) bigDecimal.add(item.getM40());
            if (item.getM10() != null) bigDecimal.add(item.getM10());
            if (item.getCri() != null) bigDecimal.add(item.getCri());
            if (item.getCsr() != null) bigDecimal.add(item.getCsr());
            // 重新计算结算价格
            if (bigDecimal.compareTo(new BigDecimal(0)) != 0) {
                item.setSettlementPrice(item.getSettlementPrice().add(bigDecimal));
            }
            // 计算结算数量（暂不知计算公式）

            // 满足条件进行扣水（暂不知扣水公式）
            if (item.getDeductWater() != null && item.getDeductWater() == 1) {
                // 扣水
            }
            // 重新计算结算总金额
            if (item.getSettlementAmount() != null) {
                BigDecimal bigDecimal1 = item.getSettlementAmount().multiply(item.getSettlementPrice());
                // 运费
                BigDecimal bigDecimal2 = item.getSettlementAmount().multiply(item.getFreight());
                // 总金额+运费
                if (item.getPriceType() != null && item.getPriceType() == 0) {
                    bigDecimal1.add(bigDecimal2);
                }
                // 总金额-运费
                if (item.getPriceType() != null && item.getPriceType() == 2) {
                    bigDecimal1.subtract(bigDecimal2);
                }
                item.setMoneySum(bigDecimal1);
            }
        }
        return list;
    }

    /**
     * 纯碱
     */
    @Override
    public List<Finance9ListResult> list23(FinanceList3Param param) {
        List<Finance9ListResult> list = financeMapper.list23(param);
        // 合计
        Finance9ListResult entity = new Finance9ListResult();
        entity.setCompanyName("合计");
        entity.setWeighbridgeWeight(new BigDecimal(0));
        entity.setSettlementPriceSum(new BigDecimal(0));
        entity.setSettlementPriceSumNo(new BigDecimal(0));
        int serialNumber = 0;
        for (Finance9ListResult item : list) {
            serialNumber++;
            if (item.getWeighbridgeWeight() == null) item.setWeighbridgeWeight(new BigDecimal(0));
            if (item.getSettlementPrice() == null) item.setSettlementPrice(new BigDecimal(0));
            if (item.getSettlementPriceNo() == null) item.setSettlementPriceNo(new BigDecimal(0));
            if (item.getSettlementPriceSum() == null) item.setSettlementPriceSum(new BigDecimal(0));
            if (item.getSettlementPriceSumNo() == null) item.setSettlementPriceSumNo(new BigDecimal(0));
            // 计算合计
            entity.setWeighbridgeWeight(entity.getWeighbridgeWeight().add(item.getWeighbridgeWeight()));
            entity.setSettlementPriceSum(entity.getSettlementPriceSum().add(item.getSettlementPriceSum()));
            entity.setSettlementPriceSumNo(entity.getSettlementPriceSumNo().add(item.getSettlementPriceSumNo()));
            // 格式化数量字段
            item.getWeighbridgeWeight().setScale(2, BigDecimal.ROUND_HALF_UP);
            item.getSettlementPrice().setScale(2, BigDecimal.ROUND_HALF_UP);
            item.getSettlementPriceNo().setScale(4, BigDecimal.ROUND_HALF_UP);
            item.getSettlementPriceSum().setScale(2, BigDecimal.ROUND_HALF_UP);
            item.getSettlementPriceSumNo().setScale(4, BigDecimal.ROUND_HALF_UP);
            item.setSerialNumber(serialNumber);
        }
        // 格式化合计
        entity.getWeighbridgeWeight().setScale(2, BigDecimal.ROUND_HALF_UP);
        entity.getSettlementPriceSum().setScale(2, BigDecimal.ROUND_HALF_UP);
        entity.getSettlementPriceSumNo().setScale(4, BigDecimal.ROUND_HALF_UP);
//        list.add(entity);
        return list;
    }

    @Override
    public List<Finance9ListDtResult> list23Dt(FinanceList3Param param) {
        return financeMapper.list23Dt(param);
    }

    // 甲醇财务报表-甲醇火车
    @Override
    public List<Finance8List3Result> list24(Finance8List3Param param) {
        // 最终返回数据集合
        List<Finance8List3Result> results = new ArrayList<>();
        // 查询的原数据
        List<Finance8List3Bo> list = financeMapper.list24(param);
        // 合计对象
        Finance8List3Result total = new Finance8List3Result();
        total.setCompanyName("合计");
        total.setSettlementWeight(new BigDecimal(0)); // 数量
        total.setSettlementPriceSum(new BigDecimal(0)); // 含税物料总价
        total.setFreightSum(new BigDecimal(0)); // 含税运费
        total.setMoneySum(new BigDecimal(0)); // 总价
//    total.setSettlementPriceSumNo(new BigDecimal(0)); // 不含税物料总价
//    total.setFreightSumNo(new BigDecimal(0)); // 不含税运费
        total.setCarNumber(0); // 列数
        // 序号
        int serialNumber = 0;
        for (Finance8List3Bo bo : list) {
            serialNumber++;
            Finance8List3Result item = CglibUtil.copy(bo, Finance8List3Result.class);
            // 计算结果
            // 含税物料总价
            BigDecimal settlementPriceSum = bo.getSettlementWeight()
                    .multiply(bo.getSettlementPrice())
                    .setScale(2, BigDecimal.ROUND_HALF_UP);
            // 含税运费
            BigDecimal freightSum = bo.getSettlementWeight()
                    .multiply(bo.getFreight())
                    .setScale(2, BigDecimal.ROUND_HALF_UP);
            // 含税装车费
            BigDecimal installSum = bo.getSettlementWeight()
                    .multiply(bo.getInstallCost())
                    .setScale(2, BigDecimal.ROUND_HALF_UP);
            // 含税包装费
            BigDecimal packageSum = bo.getSettlementWeight()
                    .multiply(bo.getPackageCost())
                    .setScale(2, BigDecimal.ROUND_HALF_UP);
            // 含税专线费
            BigDecimal specialSum = bo.getSpecialCost();
            // 含税其他费
            BigDecimal otherSum = bo.getOtherCost();
            // 总价
            BigDecimal moneySum = settlementPriceSum.add(freightSum).add(installSum).add(specialSum).add(otherSum);
            // 不含税物料总价
//      BigDecimal settlementPriceSumNo = FinanceUtil.computeNoTax(settlementPriceSum, bo.getTaxRate());
            // 不含税运费
//      BigDecimal freightSumNo = new BigDecimal(0);
            // 设置计算后的字段
            item.setSettlementPriceSum(settlementPriceSum);
            item.setFreightSum(freightSum);
            item.setInstallSum(installSum);
            item.setPackageSum(packageSum);
            item.setSpecialSum(specialSum);
            item.setOtherSum(otherSum);
            item.setMoneySum(moneySum);
//      item.setFreightSumNo(freightSumNo);
//      item.setSettlementPriceSumNo(settlementPriceSumNo);
            item.setSerialNumber(serialNumber);
            results.add(item);
            // 计算合计
            total.setSettlementWeight(total.getSettlementWeight().add(bo.getSettlementWeight()));
            total.setSettlementPriceSum(total.getSettlementPriceSum().add(settlementPriceSum));
            total.setFreightSum(total.getFreightSum().add(freightSum));
//      total.setFreightSumNo(total.getFreightSumNo().add(freightSumNo));
            total.setMoneySum(total.getMoneySum().add(moneySum));
//      total.setSettlementPriceSumNo(total.getSettlementPriceSumNo().add(settlementPriceSumNo));
            total.setCarNumber(total.getCarNumber() + bo.getCarNumber());
        }
        results.add(total);
        return results;
    }

    // 甲醇明细报表
    @Override
    public List<Finance8List4Result> list25(Finance8List4Param param) {
        // 最终返回数据集合
        List<Finance8List4Result> results = new ArrayList<>();
        // 查询的原数据
        List<Finance8List4Bo> list = financeMapper.list25(param);
        Map<String, List<Finance8List4Bo>> collect1 = list.stream().collect(
                Collectors.groupingBy(Finance8List4Bo::getId, Collectors.toList()));
        System.out.println("姓名重复计数情况：" + collect1);
        Map<Object, Long> collect2 = list.stream().collect(
                Collectors.groupingBy(Finance8List4Bo::getId, Collectors.counting()));
        System.out.println("姓名重复计数情况：" + collect2);
        //筛出有重复的姓名
        List<String> collect3 = collect1.keySet().stream().
                filter(key -> collect2.get(key) > 1).collect(Collectors.toList());
        //可以知道有哪些姓名有重复
        System.out.println("方法2-重复的姓名 ： " + collect3);
        for (String str : collect3) {
            Finance8List4Bo finance8List4Bo = new Finance8List4Bo();
            //0>1
            if (collect1.get(str).get(0).getWeighbridgeWeight().compareTo(collect1.get(str).get(1).getWeighbridgeWeight()) == 1) {
                finance8List4Bo = collect1.get(str).get(0);
                finance8List4Bo.setWeighbridgeWeight(collect1.get(str).get(0).getWeighbridgeWeight().subtract(collect1.get(str).get(1).getWeighbridgeWeight()));
            } else {
                finance8List4Bo = collect1.get(str).get(1);
                finance8List4Bo.setWeighbridgeWeight(collect1.get(str).get(1).getWeighbridgeWeight().subtract(collect1.get(str).get(0).getWeighbridgeWeight()));
            }
            for (Finance8List4Bo finance8List4Bo1 : list) {
                if (finance8List4Bo1.getId().equals(str) && collect1.get(str).get(0).getWeighbridgeWeight().compareTo(finance8List4Bo1.getWeighbridgeWeight()) == 0) {
                    finance8List4Bo1 = finance8List4Bo;
                }
            }
        }
        // 小计对象
        Finance8List4Result subtotal = new Finance8List4Result();
        subtotal.setCompanyName("小计");
        subtotal.setWeighbridgeWeight(new BigDecimal(0)); // 数量
        subtotal.setSettlementPriceSum(new BigDecimal(0)); // 含税物料总价
        subtotal.setFreightSum(new BigDecimal(0)); // 含税运费
        subtotal.setMoneySum(new BigDecimal(0)); // 总价
//    subtotal.setSettlementPriceSumNo(new BigDecimal(0)); // 不含税物料总价
//    subtotal.setFreightSumNo(new BigDecimal(0)); // 不含税运费
        // 合计对象
        Finance8List4Result total = new Finance8List4Result();
        total.setCompanyName("合计");
        total.setWeighbridgeWeight(new BigDecimal(0)); // 数量
        total.setSettlementPriceSum(new BigDecimal(0)); // 含税物料总价
        total.setFreightSum(new BigDecimal(0)); // 含税运费
        total.setMoneySum(new BigDecimal(0)); // 总价
//    total.setSettlementPriceSumNo(new BigDecimal(0)); // 不含税物料总价
//    total.setFreightSumNo(new BigDecimal(0)); // 不含税运费
        String companyName = list.size() > 0 ? list.get(0).getCompanyName() : "";
        // 序号
        int serialNumber = 0;
        for (Finance8List4Bo bo : list) {
            serialNumber++;
            Finance8List4Result item = CglibUtil.copy(bo, Finance8List4Result.class);
            // 计算结果
            // 含税物料总价
            BigDecimal settlementPriceSum = bo.getWeighbridgeWeight()
                    .multiply(bo.getSettlementPrice())
                    .setScale(2, BigDecimal.ROUND_HALF_UP);
            // 含税运费
            BigDecimal freightSum = bo.getWeighbridgeWeight()
                    .multiply(bo.getFreight())
                    .setScale(2, BigDecimal.ROUND_HALF_UP);
            // 含税装车费
            BigDecimal installSum = bo.getWeighbridgeWeight()
                    .multiply(bo.getInstallCost())
                    .setScale(2, BigDecimal.ROUND_HALF_UP);
            // 含税包装费
            BigDecimal packageSum = bo.getWeighbridgeWeight()
                    .multiply(bo.getPackageCost())
                    .setScale(2, BigDecimal.ROUND_HALF_UP);
            // 含税专线费
            BigDecimal specialSum = bo.getSpecialCost();
            // 含税其他费
            BigDecimal otherSum = bo.getOtherCost();
            // 总价
            BigDecimal moneySum = settlementPriceSum.add(freightSum).add(installSum).add(specialSum).add(otherSum);
            // 不含税物料总价
//      BigDecimal settlementPriceSumNo = FinanceUtil.computeNoTax(settlementPriceSum, bo.getTaxRate());
            // 不含税运费
//      BigDecimal freightSumNo = FinanceUtil.computeNoTax(freightSum, bo.getTaxRate());
            // 设置计算后的字段
            item.setSettlementPriceSum(settlementPriceSum);
            item.setFreightSum(freightSum);
            item.setInstallSum(installSum);
            item.setPackageSum(packageSum);
            item.setMoneySum(moneySum);
            item.setSpecialSum(specialSum);
            item.setOtherSum(otherSum);
//      item.setFreightSumNo(freightSumNo);
//      item.setSettlementPriceSumNo(settlementPriceSumNo);
            item.setSerialNumber(serialNumber);
            results.add(item);
            // 计算小计
            subtotal.setWeighbridgeWeight(subtotal.getWeighbridgeWeight().add(bo.getWeighbridgeWeight()));
            subtotal.setSettlementPriceSum(subtotal.getSettlementPriceSum().add(settlementPriceSum));
//      subtotal.setFreightSum(total.getFreightSum().add(freightSum));
//      subtotal.setFreightSumNo(total.getFreightSumNo().add(freightSumNo));
            subtotal.setMoneySum(subtotal.getMoneySum().add(moneySum));
//      subtotal.setSettlementPriceSumNo(subtotal.getSettlementPriceSumNo().add(settlementPriceSumNo));
            if (serialNumber == list.size() || !companyName.equals(list.get(serialNumber).getCompanyName())) {
                results.add(CglibUtil.copy(subtotal, Finance8List4Result.class));
                companyName = serialNumber != list.size() ? list.get(serialNumber).getCompanyName() : "";
                subtotal.setWeighbridgeWeight(new BigDecimal(0)); // 数量
                subtotal.setSettlementPriceSum(new BigDecimal(0)); // 含税物料总价
//        subtotal.setFreightSum(new BigDecimal(0)); // 含税运费
                subtotal.setMoneySum(new BigDecimal(0)); // 总价
//        subtotal.setFreightSumNo(new BigDecimal(0)); // 不含税运费
            }
            // 计算合计
            total.setWeighbridgeWeight(total.getWeighbridgeWeight().add(bo.getWeighbridgeWeight()));
            total.setSettlementPriceSum(total.getSettlementPriceSum().add(settlementPriceSum));
//      total.setFreightSum(total.getFreightSum().add(freightSum));
//      total.setFreightSumNo(total.getFreightSumNo().add(freightSumNo));
            total.setMoneySum(total.getMoneySum().add(moneySum));
//      total.setSettlementPriceSumNo(total.getSettlementPriceSumNo().add(settlementPriceSumNo));
        }
        results.add(total);
        return results;
    }

    // 焦炭派车单列表
    @Override
    public List<Finance7List2Result> list26(Finance7ListParam param) {
        List<Finance7List2Result> results = new ArrayList<>();
        List<Finance7ListBo> list = financeMapper.list26(param);
        for (Finance7ListBo bo : list) {
            Finance7List2Result item = CglibUtil.copy(bo, Finance7List2Result.class);
            // 检验化权为出厂时，才有质检（取质检数据）方便测试临时处理==null情况
            if (bo.getInspection() == null || bo.getInspection() == 0) {
                if (StrUtil.isEmpty(bo.getResult())) continue;
                // 取质检数据
                item.setWater(getFieldValue(bo.getResult(), 939)); // 全水分
                item.setAsh(getFieldValue(bo.getResult(), 930)); // 灰分
                item.setVolatilize(getFieldValue(bo.getResult(), 931)); // 挥发分
                item.setSulfur(getFieldValue(bo.getResult(), 932)); // 硫分
                item.setFoam(getFieldValue(bo.getResult(), 938)); // 焦沫含量
                item.setM40(getFieldValue(bo.getResult(), 933)); // m40
                item.setM10(getFieldValue(bo.getResult(), 935)); // m10
                item.setCri(getFieldValue(bo.getResult(), 936)); // cri
                item.setCsr(getFieldValue(bo.getResult(), 937)); // csr
            }
            results.add(item);
        }
        return results;
    }

    // 余额查询（废弃）
    @Override
    @Deprecated
    public List<Finance10Result> list27(Finance10Param param) {
        List<Finance10Result> results = new ArrayList<>();
        List<Finance10Bo> list = financeMapper.list27(param);
        for (Finance10Bo bo : list) {
            Finance10Result item = new Finance10Result();
//      item.setCompanyName(bo.getCompanyName());
            BigDecimal cashRemittance = new BigDecimal(0); // 现金汇款
            BigDecimal acceptanceOfTheRemittance = new BigDecimal(0); // 承兑汇款
            BigDecimal transferAccount = new BigDecimal(0); // 转账
            BigDecimal paymentForGood = new BigDecimal(0); // 本月货款
            BigDecimal beforeBalance = new BigDecimal(0); // 上月余额
            BigDecimal balance = new BigDecimal(0); // 余额
            LocalDateTime date1 = LocalDateTimeUtil.parse("2069-01-01T00:00:00"); // 用于计算上月余额的时间
            LocalDateTime date2 = LocalDateTimeUtil.parse("1999-01-01T00:00:00"); // 用于计算余额的时间
            for (Finance10BoCol data : bo.getCol()) {
                // 取物料名称
//        if (item.getMaterialName() == null) {
//          if (data.getMaterialName() != null) item.setMaterialName(data.getMaterialName());
//        }
                // 计算现金汇款
                cashRemittance = cashRemittance.add(data.getCashRemittance());
                // 计算承兑汇款
                acceptanceOfTheRemittance = acceptanceOfTheRemittance.add(data.getAcceptanceOfTheRemittance());
                // 计算转账
                transferAccount = transferAccount.add(data.getTransferAccount());
                // 计算本月货款
                paymentForGood = paymentForGood.add(data.getPaymentForGood());
                // 计算上月余额
                if (LocalDateTimeUtil.between(data.getCreatedAt(), date1).getSeconds() > 0) {
                    date1 = data.getCreatedAt();
                    beforeBalance = data.getBeforeChange();
                }
                // 计算余额
                if (LocalDateTimeUtil.between(data.getCreatedAt(), date2).getSeconds() < 0) {
                    date2 = data.getCreatedAt();
                    balance = data.getAfterChange();
                }
            }
            item.setCashRemittance(cashRemittance);
            item.setBalance(balance);
            item.setBeforeBalance(beforeBalance);
            item.setAcceptanceOfTheRemittance(acceptanceOfTheRemittance);
            item.setPaymentForGoods(paymentForGood);
            item.setTransferAccounts(transferAccount);
            results.add(item);
        }
        return results;
    }

    // 余额查询列表
    @Override
    public List<Finance10Result> list28(Finance10JcParam param) {
        TimeInterval timer = DateUtil.timer();
        // 查询对象
        Finance10Param param1 = new Finance10Param();
        param1.setMaterialId(param.getMaterialId());
        param1.setSupplierId(param.getSupplierId());
        param1.setCategoryId(param.getCategoryId());
        // 根据不同月份设置查询的开始日期和结束日期
        switch (param.getMonth()) {
            case 1:
                param1.setStartDate(LocalDateTimeUtil.parse(param.getYear() + "-12-31T12:00:00"));
                param1.setEndDate(LocalDateTimeUtil.parse(param.getYear() + "-01-31T23:59:59"));
                break;
            case 12:
                param1.setStartDate(LocalDateTimeUtil.parse(param.getYear() + "-11-26T00:00:00"));
                param1.setEndDate(LocalDateTimeUtil.parse(param.getYear() + "-12-31T11:59:59"));
                break;
            default:
                // 获取一个月的最后一天
                Integer endDay;
                switch (param.getMonth()) {
                    case 2:
                        endDay = (((param.getYear() & 3) == 0)
                                && ((param.getYear() % 100) != 0
                                || (param.getYear() % 400) == 0)) ? 29 : 28;
                        break;
                    case 4:
                    case 6:
                    case 9:
                    case 11:
                        endDay = 30;
                        break;
                    default:
                        endDay = 31;
                        break;
                }
                String startMonth = param.getMonth() - 1 < 10 ? "-0" + (param.getMonth() - 1) : "-" + (param.getMonth() - 1);
                String endMonth = param.getMonth() < 10 ? "-0" + param.getMonth() : "-" + param.getMonth();
                param1.setStartDate(LocalDateTimeUtil.parse(param.getYear() + startMonth + "-26T00:00:00"));
                param1.setEndDate(LocalDateTimeUtil.parse(param.getYear() + endMonth + "-" + endDay + "T23:59:59"));
                break;
        }
        List<Finance10Result> results = new ArrayList<>();
        logger.error("【余额表】设置查询条件所花费的时间：{}", timer.intervalRestart());
        List<Finance10Bo> list = financeMapper.list27(param1);
        logger.error("【余额表】数据库查询所花费的时间：{}", timer.intervalRestart());
        // 根据ID排序
        for (Finance10Bo bo : list) {
            bo.setCol(bo.getCol().stream().sorted(Comparator.comparing(Finance10BoCol::getId)).collect(Collectors.toList()));
        }
        logger.error("【余额表】程序上排序花费时间：{}", timer.intervalRestart());
        // 计算正常数据的处理范围
        for (Finance10Bo bo : list) {
            Finance10Result item = new Finance10Result();
            item.setSupplierId(bo.getSupplierId());
            item.setCompanyName(bo.getCompanyName());
            item.setCustomerCredit(bo.getCustomerCredit());
            BigDecimal cashRemittance = new BigDecimal(0); // 现金汇款
            BigDecimal acceptanceOfTheRemittance = new BigDecimal(0); // 承兑汇款
            BigDecimal transferAccount = new BigDecimal(0); // 转账
            BigDecimal paymentForGood = new BigDecimal(0); // 本月货款
            BigDecimal beforeBalance = new BigDecimal(0); // 上月余额
            BigDecimal beforeBalanceOther = new BigDecimal(0); // 上月余额的转账、承兑、现金合计
            BigDecimal balance = new BigDecimal(0); // 本月余额
            BigDecimal balanceOther = new BigDecimal(0); // 本月余额的转账、承兑、现金合计
            BigDecimal otherForGood = new BigDecimal(0); // 其他货款
//      LocalDateTime date1 = LocalDateTimeUtil.parse("2069-01-01T00:00:00"); // 用于计算上月余额的时间
//      LocalDateTime date2 = LocalDateTimeUtil.parse("1999-01-01T00:00:00"); // 用于计算余额的时间
            Map<String, BigDecimal> dt = new HashMap<>(); // 物料明细
            for (Finance10BoCol data : bo.getCol()) {
                int dataMonth = data.getCreatedAt().getMonthValue(); // 数据的月份
                int dataDay = data.getCreatedAt().getDayOfMonth(); // 数据的天数
                // 2到12月的现金，承兑，转账只统计月初到月底,1月统计12月31日12:00:00到月底
                if (param.getMonth() == 1 ||
                        param.getMonth() != 1 && dataMonth == param.getMonth()) {
                    // 计算现金汇款
                    cashRemittance = cashRemittance.add(data.getCashRemittance());
                    // 计算承兑汇款
                    acceptanceOfTheRemittance = acceptanceOfTheRemittance.add(data.getAcceptanceOfTheRemittance());
                    // 计算转账
                    transferAccount = transferAccount.add(data.getTransferAccount());
                }
                // 1到12月的上月余额（最终上月余额1月份不需要再加上beforeBalanceOther）
                if (param.getMonth() - 1 == dataMonth) {
                    // 计算上月余额
                    if (beforeBalance.compareTo(new BigDecimal(0)) == 0) {
                        beforeBalance = data.getBeforeChange();
                    }
                    // 计算上月余额，转账、承兑、现汇的合
                    beforeBalanceOther = beforeBalanceOther.add(data.getCashRemittance()).add(data.getAcceptanceOfTheRemittance()).add(data.getTransferAccount());
                }
                // 1到11月的本月余额
                if (param.getMonth() != 12 && param.getMonth() == dataMonth && dataDay >= 26) {
                    // 计算本月余额
                    if (balance.compareTo(new BigDecimal(0)) == 0) {
                        balance = data.getBeforeChange();
                    }
                    balanceOther = balanceOther.add(data.getCashRemittance()).add(data.getAcceptanceOfTheRemittance()).add(data.getTransferAccount());
                }
                // 12月的本月余额
                if (param.getMonth() == 12 && data.getMaterialName() != null) {
                    balance = data.getAfterChange();
                }
                // 1到12月的货款
                if (param.getMonth() == 12 || param.getMonth() != 12
                        && (param.getMonth() == dataMonth && dataDay <= 25 || param.getMonth() - 1 == dataMonth && dataDay >= 26)) {
                    // 本月搜索项货款（无搜索项时||有物料搜索项时等于物料搜索项，无物料搜索项时等于物料大类搜索项）
                    if (data.getMaterialName() != null &&
                            ((param1.getMaterialId() == null && param1.getCategoryId() == null)
                                    || (param1.getMaterialId() != null && param1.getMaterialId() == data.getMaterialId())
                                    || (param1.getMaterialId() == null && param1.getCategoryId() == data.getCategoryId()))) {
                        // 统计本月货款
                        paymentForGood = paymentForGood.add(data.getPaymentForGood());
                        // 统计本月货款明细
                        BigDecimal bigDecimal = dt.get(data.getMaterialName());
                        if (bigDecimal != null)
                            dt.put(data.getMaterialName(), bigDecimal.add(data.getPaymentForGood()));
                        else dt.put(data.getMaterialName(), data.getPaymentForGood());
                    }
                    // 本月其他货款
                    else {
                        if (data.getMaterialName() != null) otherForGood = otherForGood.add(data.getPaymentForGood());
                    }
                }
            }
            // 保存上月余额
            if (param.getMonth() == 1) item.setBeforeBalance(beforeBalance);
            else item.setBeforeBalance(beforeBalance.add(beforeBalanceOther));
            if (item.getBeforeBalance().compareTo(new BigDecimal(0)) == 0) {
                Finance10Param param2 = new Finance10Param();
                param2.setStartDate(param1.getStartDate());
                param2.setSupplierId(bo.getSupplierId());
                Finance10Bo list1 = financeMapper.checkBalance(param2);
                if (list1 != null && list1.getCustomerCredit() != null) {
                    item.setBeforeBalance(list1.getCustomerCredit());
                }
            }
            // 保存本月余额
            if (param.getMonth() == 12) item.setBalance(balance);
            else item.setBalance(balance.add(balanceOther));
            // 保存其他信息
            item.setCashRemittance(cashRemittance);
            item.setAcceptanceOfTheRemittance(acceptanceOfTheRemittance);
            item.setPaymentForGoods(paymentForGood);
            item.setTransferAccounts(transferAccount);
            item.setOtherForGood(otherForGood);
            if (!dt.isEmpty()) item.setDt(dt);
            results.add(item);
        }
//        for (Finance10Result finance10Result : results) {
//            yueParam yueParam = new yueParam();
//            if (param.getMonth() < 10) {
//                yueParam.setTb2endDate(LocalDateTimeUtil.parse(param.getYear() + "-0" + param.getMonth() + "-25T23:59:59"));
//            } else {
//                yueParam.setTb2endDate(LocalDateTimeUtil.parse(param.getYear() + "-" + param.getMonth() + "-25T23:59:59"));
//            }
//            yueParam.setTb2startDate(param1.getStartDate());
//
//            if (param.getMonth() < 10) {
//                yueParam.setTb1endDate(param.getYear() + "-0" + param.getMonth());
//            } else {
//                yueParam.setTb1endDate(param.getYear() + "-" + param.getMonth());
//            }
//            if (finance10Result.getSupplierId() == null && finance10Result.getSupplierId().equals("")) {
//                continue;
//            }
//            System.out.println("System.out.println;" + finance10Result.getSupplierId());
//            yueParam.setCustomerUserId(finance10Result.getSupplierId());
//            MonthlyBalanceBo monthlyBalanceBo = new MonthlyBalanceBo();
//            MonthlyBalanceBo monthlyBalanceBoss = financeMapper.getTb1Tb2(yueParam);
//            // 货款
//            if (monthlyBalanceBoss != null && monthlyBalanceBoss.getPayment() != null && monthlyBalanceBoss.getPayment().compareTo(new BigDecimal(0)) != 0) {
//                monthlyBalanceBo.setPayment(monthlyBalanceBoss.getPayment());
//            }
//            // 入账单
//            if (monthlyBalanceBoss != null && monthlyBalanceBoss.getBilling() != null && monthlyBalanceBoss.getBilling().compareTo(new BigDecimal(0)) != 0) {
//                monthlyBalanceBo.setBilling(monthlyBalanceBoss.getBilling());
//            }
//            // 公司id
//            monthlyBalanceBo.setSupplierId(finance10Result.getSupplierId());
//            // 公司名称
//            monthlyBalanceBo.setCompanyName(finance10Result.getCompanyName());
//            // 余额日期
//            if (param.getMonth() < 10) {
//                monthlyBalanceBo.setBalanceDate(param.getYear() + "-0" + param.getMonth());
//            } else {
//                monthlyBalanceBo.setBalanceDate(param.getYear() + "-" + param.getMonth());
//            }
//            BigDecimal afterChange=    financeMapper.getAfterChange(finance10Result.getSupplierId());
//            if (afterChange!=null){
//                // 期初余额
//                monthlyBalanceBo.setOpeningBalance(afterChange);
//            }
//            String startMonth = param.getMonth() - 1 < 10 ? "-0" + (param.getMonth() - 1) : "-" + (param.getMonth() - 1);
//            LocalDateTime startDate = LocalDateTimeUtil.parse(param.getYear() + startMonth + "-26T00:00:00");
//            LocalDateTime endDate = LocalDateTimeUtil.parse(param.getYear() + startMonth + "-" + endDay(param.getYear(),param.getMonth()-1) + "T23:59:59");
//            // 获取月末入账单
//            MonthlyBalanceBo monthlyBalanceBo1 = financeMapper.getBilling(monthlyBalanceBo.getSupplierId(), startDate, endDate);
//            if (monthlyBalanceBo1 != null && monthlyBalanceBo1.getBilling() != null)
//            {
//                // 期末余额
//                monthlyBalanceBo.setEndingBalance(monthlyBalanceBo.getOpeningBalance().add(monthlyBalanceBo.getBilling().add(monthlyBalanceBo1.getBilling())).subtract(monthlyBalanceBo.getPayment()));
//            }
//        else{
//            monthlyBalanceBo.setEndingBalance(monthlyBalanceBo.getOpeningBalance().add(monthlyBalanceBo.getBilling()).subtract(monthlyBalanceBo.getPayment()));
//        }
//            LocalDateTime dateTime = LocalDateTime.now();
//            monthlyBalanceBo.setCreatedTime(dateTime);
//            financeMapper.getInsertSupplier(monthlyBalanceBo);
//        }


//        List<MonthlyBalanceBo> monthlyBalanceBos = financeMapper.getMonthlyBalanceBos();
//        for (MonthlyBalanceBo finance10Result : monthlyBalanceBos) {
//            Integer supplierId =finance10Result.getSupplierId();
//            yueParam yueParam = new yueParam();
//            yueParam.setTb2startDate(LocalDateTimeUtil.parse("2021-09-26T00:00:00"));
//            yueParam.setTb2endDate(LocalDateTimeUtil.parse("2021-10-25T23:59:59"));
//            yueParam.setTb1endDate("2021-10");
//            System.out.println("System.out.println;" + supplierId);
//            yueParam.setCustomerUserId(supplierId);
//            MonthlyBalanceBo monthlyBalanceBo = new MonthlyBalanceBo();
//            // 获取上一个月的余额记录
//            MonthlyBalanceBo  monthlyBalanceBoss = financeMapper.getTb1Tb2(yueParam);
//            //获取 9月底的入账单
//            MonthlyBalanceBo monthlyBalanceBo2 = financeMapper.getBill(supplierId);
//            // 货款
//            if (monthlyBalanceBoss!=null&&monthlyBalanceBoss.getPayment()!=null&&monthlyBalanceBoss.getPayment().compareTo(new BigDecimal(0))!=0){
//                monthlyBalanceBo.setPayment(monthlyBalanceBoss.getPayment());
//            }
//            // 入账单
//            if (monthlyBalanceBoss!=null&&monthlyBalanceBoss.getBilling()!=null&&monthlyBalanceBoss.getBilling().compareTo(new BigDecimal(0))!=0){
//                monthlyBalanceBo.setBilling(monthlyBalanceBoss.getBilling());
//            }
//            //公司id
//            monthlyBalanceBo.setSupplierId(supplierId);
//            // 公司名称
//            monthlyBalanceBo.setCompanyName(finance10Result.getCompanyName());
//            // 余额日期
//            monthlyBalanceBo.setBalanceDate("2021-10");
//            // 期初余额
//            if (monthlyBalanceBo2!=null){
//                monthlyBalanceBo.setOpeningBalance(finance10Result.getEndingBalance());
//            }
//            if (monthlyBalanceBo2 != null  ){
//                monthlyBalanceBo.setEndingBalance(monthlyBalanceBo.getOpeningBalance().add(monthlyBalanceBo.getBilling().add(monthlyBalanceBo2.getBilling())).subtract(monthlyBalanceBo.getPayment()));
//            }else{
//                monthlyBalanceBo.setEndingBalance(monthlyBalanceBo.getOpeningBalance().add(monthlyBalanceBo.getBilling()).subtract(monthlyBalanceBo.getPayment()));
//            }
//            LocalDateTime dateTime = LocalDateTime.now();
//            monthlyBalanceBo.setCreatedTime(dateTime);
//            financeMapper.getInsertSupplier(monthlyBalanceBo);
//        }
        logger.error("【余额表】计算数据所花费的时间：" + timer.intervalRestart());
        return results;
    }


    @Override
    public List<Finance3HgylcgrbbResult> list29(Finance10Param param) {


        List<Finance3HgylcgrbbBo> list = financeMapper.list29(param);
        // 新数据集合
        List<Finance3HgylcgrbbResult> results = new ArrayList<>();
        // 合计
        Finance3HgylcgrbbResult total = new Finance3HgylcgrbbResult();

        // 按物料分类
        Map<String, List<Finance3HgylcgrbbBo>> collect1 = list.stream().collect(
                Collectors.groupingBy(Finance3HgylcgrbbBo::getMaterialName, Collectors.toList()));
        for (String str : collect1.keySet()) {
            // 按物料小计
            Finance3HgylcgrbbResult subtotal = new Finance3HgylcgrbbResult();
            // 按供应商分类
            Map<String, List<Finance3HgylcgrbbBo>> collect2 = collect1.get(str).stream()
                    .sorted(Comparator.comparing(Finance3HgylcgrbbBo::getType))
                    .collect(Collectors.groupingBy(Finance3HgylcgrbbBo::getCompanyName, Collectors.toList()));
            List<Finance3HgylcgrbbResult> finance3HgylcgrbbResults = new ArrayList<>();
            for (String str1 : collect2.keySet()) {
                //按供应商统计
                Finance3HgylcgrbbResult fnone = new Finance3HgylcgrbbResult();
                int index = 0;
                for (Finance3HgylcgrbbBo finance3HgylcgrbbBo : collect2.get(str1)) {
                    if (finance3HgylcgrbbBo.getFreight() != null && finance3HgylcgrbbBo.getFreight().compareTo(new BigDecimal(0)) != 0) {
                        // 运费单价赋值
                        fnone.setFreight(finance3HgylcgrbbBo.getFreight());
                    }
                    // 物料名称
                    fnone.setMaterialName(finance3HgylcgrbbBo.getMaterialName());
                    // 供应商
                    fnone.setCompanyName(finance3HgylcgrbbBo.getCompanyName());
                    if (finance3HgylcgrbbBo.getType() == 1) {
                        fnone.setTypeStr("直供厂");
                        // 累计金额 (金额=单价*原发)
//                        fnone.setAmount(fnone.getAmount().add(finance3HgylcgrbbBo.getSettlementPrice().multiply(finance3HgylcgrbbBo.getNetWeight())));
                        // 运费金额累计(运费金额=运费单价*原发)
                        fnone.setFreightAmount(fnone.getFreightAmount().add(finance3HgylcgrbbBo.getFreight().multiply(finance3HgylcgrbbBo.getNetWeight())));
                    } else if (finance3HgylcgrbbBo.getType() == 2) {
                        fnone.setTypeStr("贸易商");
                        // 累计金额 (金额=单价*实收)
//                        fnone.setAmount(fnone.getAmount().add(finance3HgylcgrbbBo.getSettlementPrice().multiply(finance3HgylcgrbbBo.getWeighbridgeWeight())));
                        // 运费金额累计(运费金额=运费单价*实收)
                        fnone.setFreightAmount(fnone.getFreightAmount().add(finance3HgylcgrbbBo.getFreight().multiply(finance3HgylcgrbbBo.getWeighbridgeWeight())));
                    }
                    // 累计原发
                    fnone.setNetWeight(fnone.getNetWeight().add(finance3HgylcgrbbBo.getNetWeight()));
                    // 累计实收
                    fnone.setWeighbridgeWeight(fnone.getWeighbridgeWeight().add(finance3HgylcgrbbBo.getWeighbridgeWeight()));
                    // 单价赋值
                    fnone.setSettlementPrice(finance3HgylcgrbbBo.getSettlementPrice());
                    // 车数
                    fnone.setPlateNumber(fnone.getPlateNumber() + 1);
                    if(collect2.get(str1).size()-1 == index){
                        //累计金额 (金额=单价*原发)
                        if("直供厂".equals(fnone.getTypeStr()))fnone.setAmount(finance3HgylcgrbbBo.getSettlementPrice().multiply(fnone.getNetWeight()));
                        if("贸易商".equals(fnone.getTypeStr()))fnone.setAmount(finance3HgylcgrbbBo.getSettlementPrice().multiply(fnone.getWeighbridgeWeight()));
                    }
                    index++;
                }
                // 总金额(总金额=金额+运费金额)
                fnone.setMoney(fnone.getAmount().add(fnone.getFreightAmount()));
                // 平均价(平均价=金额+运费金额)
                fnone.setAveragePrice(fnone.getMoney().divide(fnone.getWeighbridgeWeight(), 2, BigDecimal.ROUND_HALF_UP));
                finance3HgylcgrbbResults.add(fnone);
                subtotal.setMaterialName("小计");
                subtotal.setPlateNumber(subtotal.getPlateNumber() + fnone.getPlateNumber());
                subtotal.setNetWeight(subtotal.getNetWeight().add(fnone.getNetWeight()));
                subtotal.setWeighbridgeWeight(subtotal.getWeighbridgeWeight().add(fnone.getWeighbridgeWeight()));
                subtotal.setAmount(subtotal.getAmount().add(fnone.getAmount()));
                subtotal.setFreightAmount(subtotal.getFreightAmount().add(fnone.getFreightAmount()));
                subtotal.setMoney(subtotal.getMoney().add(fnone.getMoney()));
                subtotal.setAveragePrice(subtotal.getMoney().divide(subtotal.getWeighbridgeWeight(), 2, BigDecimal.ROUND_HALF_UP));
            }
            for (int i = 0; i < finance3HgylcgrbbResults.size(); i++) {
                if (finance3HgylcgrbbResults.get(i).getCompanyName().indexOf("古县晋豫") != -1
                        || finance3HgylcgrbbResults.get(i).getCompanyName().indexOf("古县利达") != -1
                        || finance3HgylcgrbbResults.get(i).getCompanyName().indexOf("交口县旺庄") != -1
                        || finance3HgylcgrbbResults.get(i).getCompanyName().indexOf("介休宏安") != -1) {
                    finance3HgylcgrbbResults.add(0, finance3HgylcgrbbResults.get(i));
                    finance3HgylcgrbbResults.remove(i + 1);
                }
            }
            for (Finance3HgylcgrbbResult fnone :
                    finance3HgylcgrbbResults) {
                results.add(fnone);
            }
            results.add(subtotal);
            total.setMaterialName("合计");
            total.setPlateNumber(total.getPlateNumber() + subtotal.getPlateNumber());
            total.setNetWeight(total.getNetWeight().add(subtotal.getNetWeight()));
            total.setWeighbridgeWeight(total.getWeighbridgeWeight().add(subtotal.getWeighbridgeWeight()));
            total.setAmount(total.getAmount().add(subtotal.getAmount()));
            total.setFreightAmount(total.getFreightAmount().add(subtotal.getFreightAmount()));
            total.setMoney(total.getMoney().add(subtotal.getMoney()));
            total.setAveragePrice(total.getMoney().divide(total.getWeighbridgeWeight(), 2, BigDecimal.ROUND_HALF_UP));
        }
//        results.add(total);
        return results;
    }

    /**
     * 回填焦炭数据
     */
    @Override
    @Transactional
    public void backfill(Finance7FillParam param) throws RuntimeException {
        List<Integer> list = financeMapper.getTruckingIdList(param);
        if (list.size() <= 0) throw new RuntimeException("未找到相关可处理数据");
        Backfill entity = CglibUtil.copy(param, Backfill.class);
        backfillService.save(entity);
        int updateCount = truckingOrderDetailsMapper.update(null,
                new LambdaUpdateWrapper<TruckingOrderDetails>()
                        .set(TruckingOrderDetails::getBackfillId, entity.getId())
                        .in(TruckingOrderDetails::getId, list)
                        .eq(TruckingOrderDetails::getBackfillId, 0)
        );
        if (updateCount != list.size()) throw new RuntimeException("数据异常，请稍后重试");
    }

    // 拆单
    @Override
    @Transactional
    public void tear(Finance3CbCd param) throws RuntimeException {
        synchronized (truckingOrderTearService) {
            // 是否已拆单
            int count = truckingOrderTearService.count(
                    new LambdaQueryWrapper<TruckingOrderTear>()
                            .eq(TruckingOrderTear::getDtId, param.getDtId()));
            if (count > 0) throw new RuntimeException("已被拆单数据禁止重复拆单");
            // 查询该数据实体
            TruckingOrderTearGetTearDataBo data = truckingOrderTearMapper.getTearData(param.getDtId());
            if (data == null) throw new RuntimeException("数据不存在");
            // 拆单数量是否太多
            if (param.getQuantity().compareTo(data.getNetWeight()) == 1
                    || param.getQuantity().compareTo(data.getWeighbridgeWeight()) == 1)
                throw new RuntimeException("拆单数量太多");
//            if (data.getNetWeight().compareTo(data.getWeighbridgeWeight()) != 0)
//                throw new RuntimeException("存在磅差不能拆单");
//            if (data.getMoistureDeduction().compareTo(new BigDecimal(0)) == 0)
//                throw new RuntimeException("存在扣水不能拆单");
            // 保存拆单数据
            TruckingOrderTear entity = CglibUtil.copy(data, TruckingOrderTear.class);
            entity.setQuantity(param.getQuantity());
            entity.setSettlementPrice(param.getSettlementPrice());
            entity.setDtId(param.getDtId());
            entity.setMaterialId(data.getMaterialId());
            entity.setCustomerUserId(data.getCustomerUserId());
            entity.setResult(null);
            if (data.getSettlementPrice().compareTo(param.getSettlementPrice()) == 1) {
                entity.setSettlementPriceMax(data.getSettlementPrice());
            } else {
                entity.setSettlementPriceMax(param.getSettlementPrice());
            }
            try {
                truckingOrderTearService.save(entity);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                throw new RuntimeException("拆单失败，请重试");
            }
        }
    }

    // 生成结算数据
    @Transactional
    @Override
    public void settle(Finance7CreateParam param) throws RuntimeException {
        Settlement settlement = CglibUtil.copy(param, Settlement.class);
        // 查询发货时间
        if (param.getIds().size() <= 0) throw new RuntimeException("派车单数据为空");
//        String str = param.getIds().toString();
//        str = str.substring(1, str.length() - 1);
        LocalDate deliverTime = settlementMapper.getStartDate(param.getIds());
        BigDecimal weighbridgeWeight = settlementMapper.getWeighbridgeWeight(param.getIds());
        // 生成结算数据
        settlement.setVehCount(param.getIds().size()); // 车数
        settlement.setWeighbridgeWeight(weighbridgeWeight); // 净重
        settlement.setDeliverTime(deliverTime); // 发货日期
        settlement.setContractNumber(param.getContractNumber()); // 合同号
        settlementService.save(settlement);
        // 结算数据ID更新到派车单
        Integer count = settlementMapper.setBackfillId(settlement.getId(), param.getContractNumber(), param.getIds());
        if (count != param.getIds().size()) throw new RuntimeException("更新失败，请重试");
    }

    //甲醇拆单
    @Override
    @Transactional
    public void jctear(Finance25JcCd param) throws RuntimeException {
        synchronized (truckingOrderTearService) {
            // 是否已拆单
            int count = truckingOrderTearService.count(
                    new LambdaQueryWrapper<TruckingOrderTear>()
                            .eq(TruckingOrderTear::getDtId, param.getDtId()));
            if (count > 0) throw new RuntimeException("已被拆单数据禁止重复拆单");
            // 查询该数据实体
            TruckingOrderTearGetTearDataBo data = truckingOrderTearMapper.getJcTearData(param.getDtId());
            if (data == null) throw new RuntimeException("数据不存在");
            // 拆单数量是否太多
            if (param.getQuantity().compareTo(data.getWeighbridgeWeight()) == 1)
                throw new RuntimeException("拆单数量太多");
            // 保存拆单数据
            TruckingOrderTear entity = CglibUtil.copy(data, TruckingOrderTear.class);
            entity.setQuantity(param.getQuantity());
            entity.setSettlementPrice(param.getSettlementPrice());
            entity.setDtId(param.getDtId());
            entity.setMaterialId(data.getMaterialId());
            entity.setCustomerUserId(data.getCustomerUserId());
            if (data.getSettlementPrice().compareTo(param.getSettlementPrice()) == 1) {
                entity.setSettlementPriceMax(data.getSettlementPrice());
            } else {
                entity.setSettlementPriceMax(param.getSettlementPrice());
            }
            try {
                truckingOrderTearService.save(entity);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                throw new RuntimeException("拆单失败，请重试");
            }
        }
    }

    @Override
    public Map<String, Object> list30(Finance10JcParam param) {
        Finance10Param param1 = new Finance10Param();
        param1.setMaterialId(param.getMaterialId());
//        param1.setSupplierId(param.getSupplierId());
//        param1.setCategoryId(param.getCategoryId());
        // 根据不同月份设置查询的开始日期和结束日期
        switch (param.getMonth()) {
            case 1:
                param1.setStartDate(LocalDateTimeUtil.parse(param.getYear() + "-01-01T00:00:00"));
                param1.setEndDate(LocalDateTimeUtil.parse(param.getYear() + "-01-25T23:59:59"));
                break;
            case 12:
                param1.setStartDate(LocalDateTimeUtil.parse(param.getYear() + "-11-26T00:00:00"));
                param1.setEndDate(LocalDateTimeUtil.parse(param.getYear() + "-12-31T11:59:59"));
                break;
            default:
                // 获取一个月的最后一天
                Integer endDay;
                switch (param.getMonth()) {
                    case 2:
                        endDay = (((param.getYear() & 3) == 0)
                                && ((param.getYear() % 100) != 0
                                || (param.getYear() % 400) == 0)) ? 29 : 28;
                        break;
                    case 4:
                    case 6:
                    case 9:
                    case 11:
                        endDay = 30;
                        break;
                    default:
                        endDay = 31;
                        break;
                }
                String startMonth = param.getMonth() - 1 < 10 ? "-0" + (param.getMonth() - 1) : "-" + (param.getMonth() - 1);
                String endMonth = param.getMonth() < 10 ? "-0" + param.getMonth() : "-" + param.getMonth();
                param1.setStartDate(LocalDateTimeUtil.parse(param.getYear() + startMonth + "-26T00:00:00"));
//                param1.setEndDate(LocalDateTimeUtil.parse(param.getYear() + endMonth + "-" + endDay + "T23:59:59"));
                param1.setEndDate(LocalDateTimeUtil.parse(param.getYear() + endMonth + "-25T23:59:59"));
                break;
        }
        // 处理数据
        List<Finance3HgyljcyhzbBo> list = financeMapper.list30(param1);
        List<Map<String, Object>> headerList = new ArrayList<>();
        Map<String,Object> hMap = new HashMap<>();
        List<Map<String,Object>> hList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("title", "日期");
        map.put("align", "center");
        map.put("width", 80);
        map.put("key", "date");
//        headerList.add(map);
        hList.add(map);
        List<Map<String, String>> hmapList = new ArrayList<>();
        // 日进
        Map<String, String> map11 = new HashMap<>();
        map11.put("title", "日进");
        map11.put("align", "center");
        map11.put("key", "hvalue");
        map11.put("width", "80");
        hmapList.add(map11);
        // 累计
        Map<String, String> map22 = new HashMap<>();
        map22.put("title", "累计");
        map22.put("align", "center");
        map22.put("key", "hvalues");
        map22.put("width", "80");
        hmapList.add(map22);

        // 合计
        Map<String, Object> companyNamemap1 = new HashMap<>();
        companyNamemap1.put("title", "合计");
        companyNamemap1.put("align", "center");
        companyNamemap1.put("width", 180);
        companyNamemap1.put("children", hmapList);
//        headerList.add(companyNamemap1);
        hList.add(companyNamemap1);
        //现选项比较少所以如此临时处理
        String title = "化工"+(param.getMaterialId() == 85 ? "煤焦油":"粗苯")
                +"进厂"+param.getMonth()+"月汇总表（"+
                (param.getType() == 1 ? "实收":"原发" )+"）";
        hMap.put("title", title);
        hMap.put("align", "center");
        hMap.put("width", 150);
        hMap.put("key", "title");
        hMap.put("children", hList);
        headerList.add(hMap);
        // 根据供应商分类
        Map<String, List<Finance3HgyljcyhzbBo>> collect3 = list.stream().collect(
                Collectors.groupingBy(Finance3HgyljcyhzbBo::getCompanyName, Collectors.toList()));
        int sum = 0;
        for (String str : collect3.keySet()) {
            sum += 1;
            List<Map<String, String>> mapList = new ArrayList<>();
            int len = str.length();
            if (len < 10) {
                len = 10;
            }
            // 日进
            Map<String, String> map1 = new HashMap<>();
            map1.put("title", "日进");
            map1.put("align", "center");
            map1.put("width", String.valueOf(((20 * len) / 2)));
            map1.put("key", "value" + sum);
            mapList.add(map1);
            // 累计
            Map<String, String> map2 = new HashMap<>();
            map2.put("title", "累计");
            map2.put("align", "center");
            map2.put("width", String.valueOf(((20 * len) / 2)));
            map2.put("key", "values" + sum);
            mapList.add(map2);
            // 公司名称
            Map<String, Object> companyNamemap = new HashMap<>();
            companyNamemap.put("title", str);
            companyNamemap.put("align", "center");

            companyNamemap.put("width", 20 * len);
            companyNamemap.put("children", mapList);
            headerList.add(companyNamemap);
        }
        //根据日期分类
        Map<String, List<Finance3HgyljcyhzbBo>> collect1 = list.stream().collect(
                Collectors.groupingBy(Finance3HgyljcyhzbBo::getFactoryOutTime, Collectors.toList()));
        List<Map.Entry<String, List<Finance3HgyljcyhzbBo>>> lists = new ArrayList<>(collect1.entrySet());
        collect1 = lists.stream()
                .sorted(Comparator.comparing(Map.Entry<String, List<Finance3HgyljcyhzbBo>>::getKey))
                .collect(
                        Collectors.toMap(
                                Map.Entry::getKey, Map.Entry<String, List<Finance3HgyljcyhzbBo>>::getValue, // key = name, value = websites
                                (oldValue, newValue) -> oldValue,       // if same key, take the old key
                                LinkedHashMap::new                      // returns a LinkedHashMap, keep order
                        ));

        List<Map<String, Object>> rowList = new ArrayList<>();
        for (String str : collect1.keySet()) {
            Map<String, Object> mapRow = new HashMap<>();
            mapRow.put("date", str);
            // 按供应商分类
            Map<String, List<Finance3HgyljcyhzbBo>> collect2 = collect1.get(str).stream().collect(
                    Collectors.groupingBy(Finance3HgyljcyhzbBo::getCompanyName, Collectors.toList()));
            for (String str1 : collect2.keySet()) {
                BigDecimal netWeight = new BigDecimal(0);
                for (Finance3HgyljcyhzbBo finance3HgyljcyhzbBo : collect2.get(str1)) {
                    if (param.getType() == 2) {
                        netWeight = netWeight.add(finance3HgyljcyhzbBo.getNetWeight());
                    } else {
                        netWeight = netWeight.add(finance3HgyljcyhzbBo.getWeighbridgeWeight());

                    }
                }
                for (Map<String, Object> map1 : headerList) {
                    if (map1.get("title").toString().equals(str1)) {
                        for (Map<String, String> map2 : (List<Map<String, String>>) map1.get("children")) {
                            if (map2.get("title").equals("日进")) {
                                mapRow.put(map2.get("key"), netWeight);
                                if (mapRow.get("hvalue") != null) {
                                    mapRow.put("hvalue", netWeight.add((BigDecimal) mapRow.get("hvalue")));
                                } else {
                                    mapRow.put("hvalue", netWeight);
                                }
                            } else if (map2.get("title").equals("累计")) {
                                if (rowList.size() < 1) {
                                    mapRow.put(map2.get("key"), netWeight);
                                } else {
                                    if (rowList.size() > 0) {

                                        for (int i = rowList.size() - 1; i >= 0; i--) {
                                            if (netWeight != null && netWeight.compareTo(new BigDecimal(0)) != 0 && rowList.get(i).get(map2.get("key")) != null) {
                                                mapRow.put(map2.get("key"), netWeight.add((BigDecimal) rowList.get(i).get(map2.get("key"))));
                                                break;
                                            } else if (netWeight == null && netWeight.compareTo(new BigDecimal(0)) == 0) {
                                                break;
                                            } else if (netWeight != null && netWeight.compareTo(new BigDecimal(0)) != 0 && i == 0) {
                                                mapRow.put(map2.get("key"), netWeight);
                                                break;
                                            }

                                        }
                                    } else {
                                        mapRow.put(map2.get("key"), netWeight);
                                    }
                                }
                            }
                        }
                        break;
                    }
                }
            }
            if (rowList.size() > 0) {
                BigDecimal a = (BigDecimal) rowList.get(rowList.size() - 1).get("hvalues");
                mapRow.put("hvalues", a.add((BigDecimal) mapRow.get("hvalue")));
            } else {
                mapRow.put("hvalues", mapRow.get("hvalue"));
            }
            rowList.add(mapRow);
        }
        Map<String, Object> results = new HashMap<>();
        results.put("header", headerList);
        results.put("row", rowList);
        return results;
    }

    @Override
    public List<Finance3HgcgwlResult> list31() {
        return financeMapper.list31();
    }

    /**
     * 甲醇厂财务报表数据处理(甲醇，副盐)
     */
    @Override
    public List<Finance8Result> list21(Finance8Param param) {
        // 最终返回数据集合
        List<Finance8Result> results = new ArrayList<>();
        // 查询的原数据
        List<Finance8Bo> list = financeMapper.list21(param);
        Map<String, List<Finance8Bo>> collect1 = list.stream().collect(
                Collectors.groupingBy(Finance8Bo::getCompanyName, Collectors.toList()));
        System.out.println("姓名重复计数情况：" + collect1);
        Map<Object, Long> collect2 = list.stream().collect(
                Collectors.groupingBy(Finance8Bo::getCompanyName, Collectors.counting()));
        System.out.println("姓名重复计数情况：" + collect2);
        //筛出有重复的姓名
        List<String> collect3 = collect1.keySet().stream().
                filter(key -> collect2.get(key) > 1).collect(Collectors.toList());
        //可以知道有哪些姓名有重复
        System.out.println("方法2-重复的姓名 ： " + collect3);
        List<Finance8Bo> finance8Bos = new ArrayList<>();
        // 以公司做分组
        for (String str : collect3) {
            Map<BigDecimal, List<Finance8Bo>> collect4 = collect1.get(str).stream().collect(
                    Collectors.groupingBy(Finance8Bo::getSettlementPrice, Collectors.toList()));
            Map<Object, Long> collect6 = collect1.get(str).stream().collect(
                    Collectors.groupingBy(Finance8Bo::getSettlementPrice, Collectors.counting()));
            List<BigDecimal> collect5 = collect4.keySet().stream().
                    filter(key -> collect6.get(key) > 1).collect(Collectors.toList());
            if (collect5.size() < 1) {
                continue;
            }
            // 以公司下的单价做分组
            for (BigDecimal bd : collect5) {
                BigDecimal a = new BigDecimal(0);
                for (Finance8Bo finance8Bo1 : collect4.get(bd)) {
                    a = a.add(finance8Bo1.getWeighbridgeWeight());
                }
                boolean flag = true;

                for (Finance8Bo finance8Bo2 : list) {
                    if (flag && finance8Bo2.getCompanyName().equals(str) && bd.compareTo(finance8Bo2.getSettlementPrice()) == 0) {
                        finance8Bo2.setWeighbridgeWeight(a);
                        flag = false;
                    } else if (!flag && finance8Bo2.getCompanyName().equals(str) && bd.compareTo(finance8Bo2.getSettlementPrice()) == 0) {
                        finance8Bos.add(finance8Bo2);
                    }
                }
            }
        }
        for (Finance8Bo finance8Bo2 : finance8Bos) {
            list.remove(finance8Bo2);
        }
        // 小计对象
        Finance8Result subtotal = new Finance8Result();
        subtotal.setCompanyName("小计");
        subtotal.setWeighbridgeWeight(new BigDecimal(0)); // 数量
        subtotal.setSettlementPriceSum(new BigDecimal(0)); // 含税物料总价
//    subtotal.setFreightSum(new BigDecimal(0)); // 含税运费
//    subtotal.setInstallSum(new BigDecimal(0)); // 含税装车费
//    subtotal.setPackageSum(new BigDecimal(0)); // 含税包装费
//    subtotal.setSpecialSum(new BigDecimal(0)); // 含税专线费
//    subtotal.setOtherSum(new BigDecimal(0)); // 含税其他费
        subtotal.setMoneySum(new BigDecimal(0)); // 含税总价
        subtotal.setSettlementPriceSumNo(new BigDecimal(0)); // 不含税物料总价
//    subtotal.setFreightSumNo(new BigDecimal(0)); // 不含税运费
//    subtotal.setInstallSumNo(new BigDecimal(0)); // 不含税装车费
//    subtotal.setSpecialSumNo(new BigDecimal(0)); // 不含税专线费
//    subtotal.setOtherSumNo(new BigDecimal(0)); // 不含税其他费
        subtotal.setMoneySumNo(new BigDecimal(0)); // 不含税总价
        // 合计对象
        Finance8Result total = new Finance8Result();
        total.setCompanyName("合计");
        total.setWeighbridgeWeight(new BigDecimal(0)); // 数量
        total.setSettlementPriceSum(new BigDecimal(0)); // 含税物料总价
//    total.setFreightSum(new BigDecimal(0)); // 含税运费
//    total.setInstallSum(new BigDecimal(0)); // 含税装车费
//    total.setSpecialSum(new BigDecimal(0)); // 含税专线费
//    total.setOtherCost(new BigDecimal(0)); // 含税其他费
        total.setMoneySum(new BigDecimal(0)); // 含税总价
        total.setSettlementPriceSumNo(new BigDecimal(0)); // 不含税物料总价
//    total.setFreightSumNo(new BigDecimal(0)); // 不含税运费
//    total.setInstallSumNo(new BigDecimal(0)); // 不含税装车费
//    total.setSpecialSumNo(new BigDecimal(0)); // 不含税专线费
//    total.setOtherCostNo(new BigDecimal(0)); // 不含税其他费
        total.setMoneySumNo(new BigDecimal(0)); // 不含税总价
        String companyName = list.size() > 0 ? list.get(0).getCompanyName() : "";
        // 序号
        int serialNumber = 0;
        for (Finance8Bo bo : list) {
            serialNumber++;
            Finance8Result item = CglibUtil.copy(bo, Finance8Result.class);
            // 计算结果
            // 含税物料总价
            BigDecimal settlementPriceSum = bo.getWeighbridgeWeight()
                    .multiply(bo.getSettlementPrice())
                    .setScale(2, BigDecimal.ROUND_HALF_UP);
            // 含税运费
            BigDecimal freightSum = bo.getWeighbridgeWeight()
                    .multiply(bo.getFreight())
                    .setScale(2, BigDecimal.ROUND_HALF_UP);
            // 含税装车费
            BigDecimal installSum = bo.getWeighbridgeWeight()
                    .multiply(bo.getInstallCost())
                    .setScale(2, BigDecimal.ROUND_HALF_UP);
            // 含税包装费
            BigDecimal packageSum = bo.getWeighbridgeWeight()
                    .multiply(bo.getPackageCost())
                    .setScale(2, BigDecimal.ROUND_HALF_UP);
            // 含税专线费
            BigDecimal specialSum = bo.getSpecialCost()
                    .setScale(2, BigDecimal.ROUND_HALF_UP);
            // 含税其他费
            BigDecimal otherCostSum = bo.getOtherCost();
            // 含税总价
            BigDecimal moneySum = settlementPriceSum.add(freightSum).add(installSum).add(specialSum).add(otherCostSum).add(packageSum);
            // 不含税物料总价
            BigDecimal settlementPriceSumNo = FinanceUtil.computeNoTax(settlementPriceSum, bo.getTaxRate());
            // 不含税运费
            BigDecimal freightSumNo = FinanceUtil.computeNoTax(freightSum, bo.getFreightTaxRate());
            // 不含税装车费
            BigDecimal installSumNo = FinanceUtil.computeNoTax(installSum, bo.getInstallTaxRate());
            // 不含税包装费
            BigDecimal packageSumNo = FinanceUtil.computeNoTax(packageSum, bo.getPackageTaxRate());
            // 不含税专线费
            BigDecimal specialSumNo = FinanceUtil.computeNoTax(specialSum, bo.getSpecialTaxRate());
            // 不含税其他费
            BigDecimal otherCostSumNo = FinanceUtil.computeNoTax(otherCostSum, bo.getOtherTaxRate());
            // 不含税总价
            BigDecimal moneySumNo = settlementPriceSumNo.add(freightSumNo).add(installSumNo).add(specialSumNo).add(otherCostSumNo).add(packageSumNo);
            // 不含税单价
            BigDecimal settlementPriceNo = FinanceUtil.computeNoTax(bo.getSettlementPrice(), bo.getTaxRate());
            // 设置计算后的字段
            item.setSettlementPriceSum(settlementPriceSum);
            item.setFreightSum(freightSum);
            item.setInstallSum(installSum);
            item.setSpecialSum(specialSum);
            item.setPackageSum(packageSum);
            item.setOtherSum(otherCostSum);
            item.setMoneySum(moneySum);
            item.setSettlementPriceNo(settlementPriceNo);
            item.setFreightSumNo(freightSumNo);
            item.setInstallSumNo(installSumNo);
            item.setPackageSumNo(packageSumNo);
            item.setSpecialSumNo(specialSumNo);
            item.setOtherSumNo(otherCostSumNo);
            item.setMoneySumNo(moneySumNo);
            item.setSettlementPriceSumNo(settlementPriceSumNo);
            item.setSerialNumber(serialNumber);
            results.add(item);
            // 计算小计
            subtotal.setWeighbridgeWeight(subtotal.getWeighbridgeWeight().add(bo.getWeighbridgeWeight()));
            subtotal.setSettlementPriceSum(subtotal.getSettlementPriceSum().add(settlementPriceSum));
//      subtotal.setFreightSum(total.getFreightSum().add(freightSum));
//      subtotal.setFreightSumNo(total.getFreightSumNo().add(freightSumNo));
            subtotal.setMoneySum(subtotal.getMoneySum().add(moneySum));
            subtotal.setMoneySumNo(subtotal.getMoneySumNo().add(moneySumNo));
            subtotal.setSettlementPriceSumNo(subtotal.getSettlementPriceSumNo().add(settlementPriceSumNo));
            if (serialNumber == list.size() || !companyName.equals(list.get(serialNumber).getCompanyName())) {
                // 计算小计单价
                if (subtotal.getWeighbridgeWeight().compareTo(new BigDecimal(0)) != 0) {
                    BigDecimal bigDecimal = subtotal.getSettlementPriceSum().divide(subtotal.getWeighbridgeWeight(), 2, BigDecimal.ROUND_DOWN);
                    subtotal.setSettlementPrice(bigDecimal);
                }
                // 计算不含税小计单价
                if (subtotal.getWeighbridgeWeight().compareTo(new BigDecimal(0)) != 0) {
                    BigDecimal bigDecimal = subtotal.getSettlementPriceSumNo().divide(subtotal.getWeighbridgeWeight(), 2, BigDecimal.ROUND_DOWN);
                    subtotal.setSettlementPriceNo(bigDecimal);
                }
                // 存入小计
                results.add(CglibUtil.copy(subtotal, Finance8Result.class));
                companyName = serialNumber != list.size() ? list.get(serialNumber).getCompanyName() : "";
                // 清空小计
                subtotal.setWeighbridgeWeight(new BigDecimal(0)); // 数量
                subtotal.setSettlementPriceSum(new BigDecimal(0)); // 含税物料总价
//        subtotal.setFreightSum(new BigDecimal(0)); // 含税运费
                subtotal.setMoneySum(new BigDecimal(0)); // 总价
                subtotal.setSettlementPriceSumNo(new BigDecimal(0)); // 不含税物料总价
//        subtotal.setFreightSumNo(new BigDecimal(0)); // 不含税运费
            }
            // 计算合计
            total.setWeighbridgeWeight(total.getWeighbridgeWeight().add(bo.getWeighbridgeWeight()));
            total.setSettlementPriceSum(total.getSettlementPriceSum().add(settlementPriceSum));
//      total.setFreightSum(total.getFreightSum().add(freightSum));
//      total.setFreightSumNo(total.getFreightSumNo().add(freightSumNo));
            total.setMoneySum(total.getMoneySum().add(moneySum));
            total.setMoneySumNo(total.getMoneySumNo().add(moneySumNo));
            total.setSettlementPriceSumNo(total.getSettlementPriceSumNo().add(settlementPriceSumNo));
        }
        // 计算合计含税单价
        if (total.getWeighbridgeWeight().compareTo(new BigDecimal(0)) != 0) {
            BigDecimal bigDecimal = total.getSettlementPriceSum().divide(total.getWeighbridgeWeight(), 2, BigDecimal.ROUND_DOWN);
            total.setSettlementPrice(bigDecimal);
        }
        // 计算合计不含税单价
        if (total.getWeighbridgeWeight().compareTo(new BigDecimal(0)) != 0) {
            BigDecimal bigDecimal = total.getSettlementPriceSumNo().divide(total.getWeighbridgeWeight(), 2, BigDecimal.ROUND_DOWN);
            total.setSettlementPriceNo(bigDecimal);
        }
        results.add(total);
        return results;
    }

    /**
     * 甲醇厂财务报表-杂醇
     */
    @Override
    public List<Finance8List2Result> list22(Finance8Param param) {
        // 最终返回数据集合
        List<Finance8List2Result> results = new ArrayList<>();
        // 查询的原数据
        List<Finance8List2Bo> list = financeMapper.list22(param);
        // 合计对象
        Finance8List2Result total = new Finance8List2Result();
        total.setCompanyName("合计");
        total.setWeighbridgeWeight(new BigDecimal(0)); // 数量
        total.setSettlementPriceSum(new BigDecimal(0)); // 含税物料总价
        total.setFreightSum(new BigDecimal(0)); // 含税运费
        total.setMoneySum(new BigDecimal(0)); // 总价
        total.setSettlementPriceSumNo(new BigDecimal(0)); // 不含税物料总价
        total.setFreightSumNo(new BigDecimal(0)); // 不含税运费
        // 序号
        int serialNumber = 0;
        for (Finance8List2Bo bo : list) {
            serialNumber++;
            Finance8List2Result item = CglibUtil.copy(bo, Finance8List2Result.class);
            // 杂醇单价=每1%浓度单价*浓度
            item.setConcentrationPrice(item.getSettlementPrice());
            item.setSettlementPrice(item.getSettlementPrice().multiply(item.getMeasuredValue()));
            // 计算结果
            // 含税物料总价
            BigDecimal settlementPriceSum = bo.getWeighbridgeWeight()
                    .multiply(item.getSettlementPrice());
            // 含税运费
            BigDecimal freightSum = bo.getWeighbridgeWeight()
                    .multiply(bo.getFreight());
            // 总价
            BigDecimal moneySum = settlementPriceSum.add(freightSum);
            // 不含税物料总价
            BigDecimal settlementPriceSumNo = FinanceUtil.computeNoTax(settlementPriceSum, bo.getTaxRate());
            // 不含税运费
            BigDecimal freightSumNo = FinanceUtil.computeNoTax(freightSum, bo.getTaxRate());
            // 设置计算后的字段
            item.setSettlementPriceSum(settlementPriceSum);
            item.setFreightSum(freightSum);
            item.setMoneySum(moneySum);
            item.setFreightSumNo(freightSumNo);
            item.setSettlementPriceSumNo(settlementPriceSumNo);
            item.setSerialNumber(serialNumber);
            results.add(item);
            // 计算合计
            total.setWeighbridgeWeight(total.getWeighbridgeWeight().add(bo.getWeighbridgeWeight()));
            total.setSettlementPriceSum(total.getSettlementPriceSum().add(settlementPriceSum).setScale(2,BigDecimal.ROUND_HALF_UP));
            //.setScale(2,BigDecimal.ROUND_HALF_UP)
            total.setFreightSum(total.getFreightSum().add(freightSum));
            total.setFreightSumNo(total.getFreightSumNo().add(freightSumNo));
            total.setMoneySum(total.getMoneySum().add(moneySum).setScale(2,BigDecimal.ROUND_HALF_UP));
            total.setSettlementPriceSumNo(total.getSettlementPriceSumNo().add(settlementPriceSumNo));
        }
        results.add(total);
        return results;
    }

    /**
     * 取水分质检值
     */
    public BigDecimal getWater(String result) {
        if (result == null) return null;
        try {
            JSONArray jsonArray = JSONArray.parseArray(result);
            for (Object obj : jsonArray) {
                JSONObject json = JSON.parseObject(obj.toString());
                String name = json.getString("chinese");
                if ("水分".equals(name) || "全水分".equals(name)) {
                    BigDecimal value = json.getBigDecimal("value");
                    return value;
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
        return null;
    }

    /**
     * 取水备注
     */
    public String getRemark(String result) {
        if (result == null) return null;
        try {
            JSONArray jsonArray = JSONArray.parseArray(result);
            for (Object obj : jsonArray) {
                JSONObject json = JSON.parseObject(obj.toString());
                String name = json.getString("chinese");
                if ("备注".equals(name)) {
                    String value = json.getString("value");
                    return value;
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
        return null;
    }

    /**
     * 取特定质检结果
     */
    public BigDecimal getWater(String result, String str) {
        if (result == null) return null;
        try {
            JSONArray jsonArray = JSONArray.parseArray(result);
            for (Object obj : jsonArray) {
                JSONObject json = JSON.parseObject(obj.toString());
                String name = json.getString("chinese");
                if (StrUtil.indexOfIgnoreCase(name, str) != -1) {
                    BigDecimal value = json.getBigDecimal("value");
                    return value;
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
        return null;
    }

    /**
     * 根据filed取质检结果
     */
    public BigDecimal getFieldValue(String result, Integer field) {
        if (result == null) return null;
        try {
            JSONArray jsonArray = JSONArray.parseArray(result);
            for (Object obj : jsonArray) {
                JSONObject json = JSON.parseObject(obj.toString());
                Integer field1 = json.getInteger("field");
                if (field1.equals(field)) {
                    BigDecimal value = json.getBigDecimal("value");
                    return value;
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
        return null;
    }

    public BigDecimal getFieldValue1(String result, String field) {
        if (result == null) return null;
        try {
            JSONArray jsonArray = JSONArray.parseArray(result);
            for (Object obj : jsonArray) {
                JSONObject json = JSON.parseObject(obj.toString());
                String field1 = json.get("chinese").toString();
                if (field1.equals(field)) {
                    BigDecimal value = json.getBigDecimal("value");
                    return value;
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
        return null;
    }

    public Map<String, List<T>> getSorted(Map<String, List<T>> collect1) {
        List<Map.Entry<String, List<T>>> lists = new ArrayList<>(collect1.entrySet());
        collect1 = lists.stream()
                .sorted(Comparator.comparing(Map.Entry<String, List<T>>::getKey))
                .collect(
                        Collectors.toMap(
                                Map.Entry::getKey, Map.Entry<String, List<T>>::getValue, // key = name, value = websites
                                (oldValue, newValue) -> oldValue,       // if same key, take the old key
                                LinkedHashMap::new                      // returns a LinkedHashMap, keep order
                        ));
        return collect1;
    }

    /**
     * 获取字符串拼音的第一个字母
     *
     * @param chinese
     * @return
     */
    public static String ToFirstChar(String chinese) {
        String pinyinStr = "";
        char[] newChar = chinese.toCharArray();  //转为单个字符
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < newChar.length; i++) {
            if (newChar[i] > 128) {
                try {
                    pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0].charAt(0);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pinyinStr += newChar[i];
            }
        }
        return pinyinStr;
    }

    /**
     * 汉字转为拼音
     *
     * @param chinese
     * @return
     */
    public static String ToPinyin(String chinese) {
        String pinyinStr = "";
        char[] newChar = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < newChar.length; i++) {
            if (newChar[i] > 128) {
                try {
                    pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0];
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pinyinStr += newChar[i];
            }
        }
        return pinyinStr;
    }

    /**
     * 炭黑厂、化工回收厂财务报表
     * type 1 客户分类开票||2 客户销售报表||3 产品明细销售报表|| 4 产品综合销售报表
     */
    @Override
    public List<Finance4KhMxResult> list33(Finance4ListParam param, Integer type) {
        List<Finance4KhMxResult> results = new ArrayList<>();
        List<Finance4KhMxResult> list1 = financeMapper.list28(param);
        // 客户分类开票
        if (type == 1) {
            // 按公司分类
            Map<String, List<Finance4KhMxResult>> collect1 = list1.stream()
                    .sorted(Comparator.comparing(Finance4KhMxResult::getCompanyName))
                    .collect(Collectors.groupingBy(Finance4KhMxResult::getCompanyName, Collectors.toList()));
            List<Map.Entry<String, List<Finance4KhMxResult>>> lists = new ArrayList<>(collect1.entrySet());
            List<Map.Entry<String, List<Finance4KhMxResult>>> listss = lists.stream()
                    .sorted(Comparator.comparing(Map.Entry<String, List<Finance4KhMxResult>>::getKey, (x, y) -> {
                        // ToFirstChar 将汉字首字母转为拼音
                        x = ToFirstChar(x).toUpperCase();
                        y = ToFirstChar(y).toUpperCase();
                        Collator clt = Collator.getInstance();
                        return clt.compare(x, y);
                    })).collect(Collectors.toList());
            collect1 = lists.stream()
                    .sorted(Comparator.comparing(Map.Entry<String, List<Finance4KhMxResult>>::getKey).reversed())
                    .collect(
                            Collectors.toMap(
                                    Map.Entry::getKey, Map.Entry<String, List<Finance4KhMxResult>>::getValue, // key = name, value = websites
                                    (oldValue, newValue) -> oldValue,       // if same key, take the old key
                                    LinkedHashMap::new                      // returns a LinkedHashMap, keep order
                            ));
//            collect1=getSorted(collect1);
            for (String str : collect1.keySet()) {
                Finance4KhMxResult subtotal = new Finance4KhMxResult();
                subtotal.setCompanyName("合计");
                subtotal.setMoney(new BigDecimal(0));
                subtotal.setAssembleMoney(new BigDecimal(0));
                subtotal.setSettlementPrice(new BigDecimal(0));
                subtotal.setMoneySum(new BigDecimal(0));
                subtotal.setWeighbridgeWeight(new BigDecimal(0));
                // 按公司分类
                Map<String, List<Finance4KhMxResult>> collect2 = collect1.get(str).stream().collect(
                        Collectors.groupingBy(item -> item.getSettlementPrice() + "_" + item.getMaterialName()));
                for (String str1 : collect2.keySet()) {
                    Finance4KhMxResult finance4KhKpResult = new Finance4KhMxResult();
                    finance4KhKpResult.setMoney(new BigDecimal(0));
                    finance4KhKpResult.setAssembleMoney(new BigDecimal(0));
                    finance4KhKpResult.setSettlementPrice(new BigDecimal(0));
                    finance4KhKpResult.setMoneySum(new BigDecimal(0));
                    finance4KhKpResult.setWeighbridgeWeight(new BigDecimal(0));
                    for (int i = 0; i < collect2.get(str1).size(); i++) {
                        finance4KhKpResult.setCompanyName(collect2.get(str1).get(i).getCompanyName());
                        finance4KhKpResult.setMaterialName(collect2.get(str1).get(i).getMaterialName());
                        finance4KhKpResult.setWeighbridgeWeight(finance4KhKpResult.getWeighbridgeWeight().add(collect2.get(str1).get(i).getWeighbridgeWeight()));
                        finance4KhKpResult.setSettlementPrice(collect2.get(str1).get(i).getSettlementPrice());
                        finance4KhKpResult.setMoney(finance4KhKpResult.getMoney().add(collect2.get(str1).get(i).getMoney()));
                        finance4KhKpResult.setAssembleMoney(finance4KhKpResult.getAssembleMoney().add(collect2.get(str1).get(i).getAssembleMoney()));
                        finance4KhKpResult.setMoneySum(finance4KhKpResult.getMoneySum().add(collect2.get(str1).get(i).getMoneySum()));
                    }
                    if (subtotal.getWeighbridgeWeight() == null || subtotal.getWeighbridgeWeight().compareTo(new BigDecimal(0)) == 0) {
                        results.add(finance4KhKpResult);
                    } else {
                        finance4KhKpResult.setCompanyName(null);
                        results.add(finance4KhKpResult);
                    }
                    subtotal.setWeighbridgeWeight(subtotal.getWeighbridgeWeight().add(finance4KhKpResult.getWeighbridgeWeight()));
                    subtotal.setMoney(subtotal.getMoney().add(finance4KhKpResult.getMoney()));
                    subtotal.setAssembleMoney(subtotal.getAssembleMoney().add(finance4KhKpResult.getAssembleMoney()));
                    subtotal.setMoneySum(subtotal.getMoneySum().add(finance4KhKpResult.getMoneySum()));
                }
                subtotal.setSettlementPrice(subtotal.getMoney().divide(subtotal.getWeighbridgeWeight(), 2, BigDecimal.ROUND_HALF_UP));
                results.add(subtotal);
            }
            return results;
        }
        // 客户销售报表
        else if (type == 2) {
            // 按公司分类
            Map<String, List<Finance4KhMxResult>> collect1 = list1.stream().collect(
                    Collectors.groupingBy(Finance4KhMxResult::getCompanyName, Collectors.toList()));
            Finance4KhMxResult subtotal1 = new Finance4KhMxResult();
            subtotal1.setCompanyName("总计");
            subtotal1.setMoney(new BigDecimal(0));
            subtotal1.setAssembleMoney(new BigDecimal(0));
            subtotal1.setSettlementPrice(new BigDecimal(0));
            subtotal1.setMoneySum(new BigDecimal(0));
            subtotal1.setWeighbridgeWeight(new BigDecimal(0));
            for (String str : collect1.keySet()) {
                Finance4KhMxResult subtotal = new Finance4KhMxResult();
                subtotal.setCompanyName("合计");
                subtotal.setMoney(new BigDecimal(0));
                subtotal.setAssembleMoney(new BigDecimal(0));
                subtotal.setSettlementPrice(new BigDecimal(0));
                subtotal.setMoneySum(new BigDecimal(0));
                subtotal.setWeighbridgeWeight(new BigDecimal(0));
                // 按公司分类
                Map<String, List<Finance4KhMxResult>> collect2 = collect1.get(str).stream().collect(
                        Collectors.groupingBy(item -> item.getSettlementPrice() + "_" + item.getMaterialName()));
                for (String str1 : collect2.keySet()) {
                    Finance4KhMxResult finance4KhKpResult = new Finance4KhMxResult();
                    finance4KhKpResult.setMoney(new BigDecimal(0));
                    finance4KhKpResult.setAssembleMoney(new BigDecimal(0));
                    finance4KhKpResult.setSettlementPrice(new BigDecimal(0));
                    finance4KhKpResult.setMoneySum(new BigDecimal(0));
                    finance4KhKpResult.setWeighbridgeWeight(new BigDecimal(0));
                    for (int i = 0; i < collect2.get(str1).size(); i++) {
                        finance4KhKpResult.setCompanyName(collect2.get(str1).get(i).getCompanyName());
                        finance4KhKpResult.setMaterialName(collect2.get(str1).get(i).getMaterialName());
                        finance4KhKpResult.setWeighbridgeWeight(finance4KhKpResult.getWeighbridgeWeight().add(collect2.get(str1).get(i).getWeighbridgeWeight()));
                        finance4KhKpResult.setSettlementPrice(collect2.get(str1).get(i).getSettlementPrice());
                        finance4KhKpResult.setMoney(finance4KhKpResult.getMoney().add(collect2.get(str1).get(i).getMoney()));
                        finance4KhKpResult.setAssembleMoney(finance4KhKpResult.getAssembleMoney().add(collect2.get(str1).get(i).getAssembleMoney()));
                        finance4KhKpResult.setMoneySum(finance4KhKpResult.getMoneySum().add(collect2.get(str1).get(i).getMoneySum()));
                    }
                    if (subtotal.getWeighbridgeWeight() == null || subtotal.getWeighbridgeWeight().compareTo(new BigDecimal(0)) == 0) {
                        results.add(finance4KhKpResult);
                    } else {
                        finance4KhKpResult.setCompanyName(null);
                        results.add(finance4KhKpResult);
                    }
                    subtotal.setWeighbridgeWeight(subtotal.getWeighbridgeWeight().add(finance4KhKpResult.getWeighbridgeWeight()));
                    subtotal.setMoney(subtotal.getMoney().add(finance4KhKpResult.getMoney()));
                    subtotal.setAssembleMoney(subtotal.getAssembleMoney().add(finance4KhKpResult.getAssembleMoney()));
                    subtotal.setMoneySum(subtotal.getMoneySum().add(finance4KhKpResult.getMoneySum()));
                }
                results.add(subtotal);
                subtotal1.setWeighbridgeWeight(subtotal1.getWeighbridgeWeight().add(subtotal.getWeighbridgeWeight()));
                subtotal1.setMoney(subtotal1.getMoney().add(subtotal.getMoney()));
                subtotal1.setAssembleMoney(subtotal1.getAssembleMoney().add(subtotal.getAssembleMoney()));
                subtotal1.setMoneySum(subtotal1.getMoneySum().add(subtotal.getMoneySum()));
            }
            results.add(subtotal1);
            return results;
        }
        // 产品明细销售报表
        else if (type == 3) {
            // 按公司分类
            Map<String, List<Finance4KhMxResult>> collect1 = list1.stream().collect(
                    Collectors.groupingBy(Finance4KhMxResult::getCompanyName, Collectors.toList()));
            for (String str : collect1.keySet()) {
                Finance4KhMxResult subtotal = new Finance4KhMxResult();
                subtotal.setCompanyName("合计");
                subtotal.setMoney(new BigDecimal(0));
                subtotal.setAssembleMoney(new BigDecimal(0));
                subtotal.setSettlementPrice(new BigDecimal(0));
                subtotal.setMoneySum(new BigDecimal(0));
                subtotal.setWeighbridgeWeight(new BigDecimal(0));
                subtotal.setAdvance(new BigDecimal(0));
                subtotal.setSpecial(new BigDecimal(0));
                subtotal.setPack(new BigDecimal(0));
                subtotal.setOther(new BigDecimal(0));
                List<Finance4KhMxResult> collect2 = collect1.get(str).stream()
                        .sorted(Comparator.comparing(Finance4KhMxResult::getMaterialName).thenComparing(Finance4KhMxResult::getFactoryOutTime))
                        .collect(Collectors.toList());
                for (Finance4KhMxResult finance4KhMxResult : collect2) {

                    if (subtotal.getWeighbridgeWeight() == null || subtotal.getWeighbridgeWeight().compareTo(new BigDecimal(0)) == 0) {
                        results.add(finance4KhMxResult);
                    } else {
                        finance4KhMxResult.setCompanyName(null);
                        results.add(finance4KhMxResult);
                    }
                    subtotal.setWeighbridgeWeight(subtotal.getWeighbridgeWeight().add(finance4KhMxResult.getWeighbridgeWeight()));
                    if (finance4KhMxResult.getSettlementPrice() != null && finance4KhMxResult.getSettlementPrice().compareTo(new BigDecimal(0)) != 0) {
                        subtotal.setSettlementPrice(new BigDecimal(0));
                    }
                    subtotal.setMoney(subtotal.getMoney().add(finance4KhMxResult.getMoney()));
                    subtotal.setAdvance(subtotal.getAdvance().add(finance4KhMxResult.getAdvance()));
                    subtotal.setSpecial(subtotal.getSpecial().add(finance4KhMxResult.getSpecial()));
                    subtotal.setPack(subtotal.getPack().add(finance4KhMxResult.getPack()));
                    subtotal.setOther(subtotal.getOther().add(finance4KhMxResult.getOther()));
                    subtotal.setAssembleMoney(subtotal.getAssembleMoney().add(finance4KhMxResult.getAssembleMoney()));
                    subtotal.setMoneySum(subtotal.getMoneySum().add(finance4KhMxResult.getMoneySum()));
                }
                results.add(subtotal);
            }
            return results;
        }
        // 产品明细销售报表
        else if (type == 4) {
            // 按公司分类
            Map<String, List<Finance4KhMxResult>> collect1 = list1.stream().collect(
                    Collectors.groupingBy(Finance4KhMxResult::getMaterialName, Collectors.toList()));
            for (String str : collect1.keySet()) {
                Finance4KhMxResult subtotal = new Finance4KhMxResult();
                subtotal.setCompanyName("合计");
                subtotal.setMoney(new BigDecimal(0));
                subtotal.setAssembleMoney(new BigDecimal(0));
                subtotal.setSettlementPrice(new BigDecimal(0));
                subtotal.setMoneySum(new BigDecimal(0));
                subtotal.setWeighbridgeWeight(new BigDecimal(0));
                subtotal.setAdvance(new BigDecimal(0));
                subtotal.setSpecial(new BigDecimal(0));
                subtotal.setPack(new BigDecimal(0));
                subtotal.setOther(new BigDecimal(0));
                List<Finance4KhMxResult> collect2 = collect1.get(str).stream()
                        .sorted(Comparator.comparing(Finance4KhMxResult::getCompanyName).thenComparing(Finance4KhMxResult::getFactoryOutTime))
                        .collect(Collectors.toList());
                for (Finance4KhMxResult finance4KhMxResult : collect2) {

                    if (subtotal.getWeighbridgeWeight() == null || subtotal.getWeighbridgeWeight().compareTo(new BigDecimal(0)) == 0) {
                        results.add(finance4KhMxResult);
                    } else {
                        finance4KhMxResult.setCompanyName(null);
                        results.add(finance4KhMxResult);
                    }
                    subtotal.setWeighbridgeWeight(subtotal.getWeighbridgeWeight().add(finance4KhMxResult.getWeighbridgeWeight()));
                    if (finance4KhMxResult.getSettlementPrice() != null && finance4KhMxResult.getSettlementPrice().compareTo(new BigDecimal(0)) != 0) {
                        subtotal.setSettlementPrice(new BigDecimal(0));
                    }
                    subtotal.setMoney(subtotal.getMoney().add(finance4KhMxResult.getMoney()));
                    subtotal.setAdvance(subtotal.getAdvance().add(finance4KhMxResult.getAdvance()));
                    subtotal.setSpecial(subtotal.getSpecial().add(finance4KhMxResult.getSpecial()));
                    subtotal.setPack(subtotal.getPack().add(finance4KhMxResult.getPack()));
                    subtotal.setOther(subtotal.getOther().add(finance4KhMxResult.getOther()));
                    subtotal.setAssembleMoney(subtotal.getAssembleMoney().add(finance4KhMxResult.getAssembleMoney()));
                    subtotal.setMoneySum(subtotal.getMoneySum().add(finance4KhMxResult.getMoneySum()));
                }
                results.add(subtotal);
            }
            return results;
        }
        //
        else if (type == 5) {
            // 按公司分类
            Map<String, List<Finance4KhMxResult>> collect1 = list1.stream().collect(
                    Collectors.groupingBy(Finance4KhMxResult::getMaterialName, Collectors.toList()));
            Finance4KhMxResult subtotal1 = new Finance4KhMxResult();
            subtotal1.setCompanyName("总计");
            subtotal1.setMoney(new BigDecimal(0));
            subtotal1.setAssembleMoney(new BigDecimal(0));
            subtotal1.setSettlementPrice(new BigDecimal(0));
            subtotal1.setMoneySum(new BigDecimal(0));
            subtotal1.setWeighbridgeWeight(new BigDecimal(0));
            for (String str : collect1.keySet()) {
                Finance4KhMxResult subtotal = new Finance4KhMxResult();
                subtotal.setCompanyName("合计");
                subtotal.setMoney(new BigDecimal(0));
                subtotal.setAssembleMoney(new BigDecimal(0));
                subtotal.setSettlementPrice(new BigDecimal(0));
                subtotal.setMoneySum(new BigDecimal(0));
                subtotal.setWeighbridgeWeight(new BigDecimal(0));
                // 按公司分类
                Map<String, List<Finance4KhMxResult>> collect2 = collect1.get(str).stream()
                        .collect(
                                Collectors.groupingBy(item -> item.getSettlementPrice() + "_" + item.getCompanyName()));
                for (String str1 : collect2.keySet()) {
                    Finance4KhMxResult finance4KhKpResult = new Finance4KhMxResult();
                    finance4KhKpResult.setMoney(new BigDecimal(0));
                    finance4KhKpResult.setAssembleMoney(new BigDecimal(0));
                    finance4KhKpResult.setSettlementPrice(new BigDecimal(0));
                    finance4KhKpResult.setMoneySum(new BigDecimal(0));
                    finance4KhKpResult.setWeighbridgeWeight(new BigDecimal(0));
                    for (int i = 0; i < collect2.get(str1).size(); i++) {
                        finance4KhKpResult.setCompanyName(collect2.get(str1).get(i).getCompanyName());
                        finance4KhKpResult.setMaterialName(collect2.get(str1).get(i).getMaterialName());
                        finance4KhKpResult.setWeighbridgeWeight(finance4KhKpResult.getWeighbridgeWeight().add(collect2.get(str1).get(i).getWeighbridgeWeight()));
                        finance4KhKpResult.setSettlementPrice(collect2.get(str1).get(i).getSettlementPrice());
                        finance4KhKpResult.setMoney(finance4KhKpResult.getMoney().add(collect2.get(str1).get(i).getMoney()));
                        finance4KhKpResult.setAssembleMoney(finance4KhKpResult.getAssembleMoney().add(collect2.get(str1).get(i).getAssembleMoney()));
                        finance4KhKpResult.setMoneySum(finance4KhKpResult.getMoneySum().add(collect2.get(str1).get(i).getMoneySum()));
                    }
                    if (subtotal.getWeighbridgeWeight() == null || subtotal.getWeighbridgeWeight().compareTo(new BigDecimal(0)) == 0) {
                        results.add(finance4KhKpResult);
                    } else {
                        finance4KhKpResult.setMaterialName(null);
                        results.add(finance4KhKpResult);
                    }
                    subtotal.setWeighbridgeWeight(subtotal.getWeighbridgeWeight().add(finance4KhKpResult.getWeighbridgeWeight()));
                    subtotal.setMoney(subtotal.getMoney().add(finance4KhKpResult.getMoney()));
                    subtotal.setAssembleMoney(subtotal.getAssembleMoney().add(finance4KhKpResult.getAssembleMoney()));
                    subtotal.setMoneySum(subtotal.getMoneySum().add(finance4KhKpResult.getMoneySum()));
                }
                subtotal.setSettlementPrice(subtotal.getMoney().divide(subtotal.getWeighbridgeWeight(), 2, BigDecimal.ROUND_HALF_UP));
                results.add(subtotal);
                subtotal1.setWeighbridgeWeight(subtotal1.getWeighbridgeWeight().add(subtotal.getWeighbridgeWeight()));
                subtotal1.setMoney(subtotal1.getMoney().add(subtotal.getMoney()));
                subtotal1.setAssembleMoney(subtotal1.getAssembleMoney().add(subtotal.getAssembleMoney()));
                subtotal1.setMoneySum(subtotal1.getMoneySum().add(subtotal.getMoneySum()));
            }
            results.add(subtotal1);
            return results;
        }

        return results;
    }

    @Override
    public List<Finance4KhXsResult> list34(Finance8Param param) {
        // 最终返回数据集合
        List<Finance4KhXsResult> results = new ArrayList<>();
        // 查询的原数据
        List<Finance8List2Bo> list = financeMapper.list22(param);
        List<Finance4KhXsResult> list1 = new ArrayList<>();
        for (Finance8List2Bo f : list) {
            Finance4KhXsResult finance4KhXsResult = new Finance4KhXsResult();
            finance4KhXsResult.setCompanyName(f.getCompanyName());
            finance4KhXsResult.setMaterialName(f.getMaterialName());
            finance4KhXsResult.setWeighbridgeWeight(f.getWeighbridgeWeight());
            finance4KhXsResult.setSettlementPrice(f.getSettlementPrice().multiply(f.getMeasuredValue()));
            finance4KhXsResult.setMoney(f.getSettlementPrice().multiply(f.getMeasuredValue()).multiply(f.getWeighbridgeWeight()));
            finance4KhXsResult.setAdvance(new BigDecimal(0));
            finance4KhXsResult.setAssembleMoney(new BigDecimal(0));
            finance4KhXsResult.setPack(new BigDecimal(0));
            finance4KhXsResult.setOther(new BigDecimal(0));
            finance4KhXsResult.setMoneySum(finance4KhXsResult.getMoney());
            list1.add(finance4KhXsResult);
        }
        Map<String, List<Finance4KhXsResult>> collect1 = list1.stream()
                .sorted(Comparator.comparing(Finance4KhXsResult::getCompanyName))
                .collect(Collectors.groupingBy(Finance4KhXsResult::getCompanyName, Collectors.toList()));
        Finance4KhXsResult subtotal1 = new Finance4KhXsResult();
        subtotal1.setCompanyName("合计");
        subtotal1.setMoney(new BigDecimal(0));
        subtotal1.setAssembleMoney(new BigDecimal(0));
        subtotal1.setSettlementPrice(new BigDecimal(0));
        subtotal1.setMoneySum(new BigDecimal(0));
        subtotal1.setWeighbridgeWeight(new BigDecimal(0));
        for (String str : collect1.keySet()) {
            Finance4KhXsResult subtotal = new Finance4KhXsResult();
            subtotal.setMaterialName("小计");
            subtotal.setMoney(new BigDecimal(0));
            subtotal.setAssembleMoney(new BigDecimal(0));
            subtotal.setSettlementPrice(new BigDecimal(0));
            subtotal.setMoneySum(new BigDecimal(0));
            subtotal.setWeighbridgeWeight(new BigDecimal(0));
            // 按公司分类
            Map<String, List<Finance4KhXsResult>> collect2 = collect1.get(str).stream().collect(
                    Collectors.groupingBy(item -> item.getSettlementPrice() + "_" + item.getMaterialName()));
            for (String str1 : collect2.keySet()) {
                Finance4KhXsResult finance4KhKpResult = new Finance4KhXsResult();
                finance4KhKpResult.setMoney(new BigDecimal(0));
                finance4KhKpResult.setAssembleMoney(new BigDecimal(0));
                finance4KhKpResult.setSettlementPrice(new BigDecimal(0));
                finance4KhKpResult.setMoneySum(new BigDecimal(0));
                finance4KhKpResult.setWeighbridgeWeight(new BigDecimal(0));
                for (int i = 0; i < collect2.get(str1).size(); i++) {
                    finance4KhKpResult.setCompanyName(collect2.get(str1).get(i).getCompanyName());
                    finance4KhKpResult.setMaterialName(collect2.get(str1).get(i).getMaterialName());
                    finance4KhKpResult.setWeighbridgeWeight(finance4KhKpResult.getWeighbridgeWeight().add(collect2.get(str1).get(i).getWeighbridgeWeight()));
                    finance4KhKpResult.setSettlementPrice(collect2.get(str1).get(i).getSettlementPrice());
                    finance4KhKpResult.setMoney(finance4KhKpResult.getMoney().add(collect2.get(str1).get(i).getMoney()));
                    finance4KhKpResult.setAssembleMoney(finance4KhKpResult.getAssembleMoney().add(collect2.get(str1).get(i).getAssembleMoney()));
                    finance4KhKpResult.setMoneySum(finance4KhKpResult.getMoneySum().add(collect2.get(str1).get(i).getMoneySum()));
                }
                if (subtotal.getWeighbridgeWeight() == null || subtotal.getWeighbridgeWeight().compareTo(new BigDecimal(0)) == 0) {
                    results.add(finance4KhKpResult);
                } else {
                    finance4KhKpResult.setCompanyName(null);
                    results.add(finance4KhKpResult);
                }
                subtotal.setWeighbridgeWeight(subtotal.getWeighbridgeWeight().add(finance4KhKpResult.getWeighbridgeWeight()));
                subtotal.setMoney(subtotal.getMoney().add(finance4KhKpResult.getMoney()));
                subtotal.setAssembleMoney(subtotal.getAssembleMoney().add(finance4KhKpResult.getAssembleMoney()));
                subtotal.setMoneySum(subtotal.getMoneySum().add(finance4KhKpResult.getMoneySum()));
            }
            subtotal.setSettlementPrice(subtotal.getMoney().divide(subtotal.getWeighbridgeWeight(), 2, BigDecimal.ROUND_HALF_UP));
            results.add(subtotal);
            subtotal1.setWeighbridgeWeight(subtotal1.getWeighbridgeWeight().add(subtotal.getWeighbridgeWeight()));
            subtotal1.setMoney(subtotal1.getMoney().add(subtotal.getMoney()));
            subtotal1.setAssembleMoney(subtotal1.getAssembleMoney().add(subtotal.getAssembleMoney()));
            subtotal1.setMoneySum(subtotal1.getMoneySum().add(subtotal.getMoneySum()));
            subtotal1.setSettlementPrice(subtotal1.getMoney().divide(subtotal1.getWeighbridgeWeight(), 2, BigDecimal.ROUND_HALF_UP));

        }
        results.add(subtotal1);
        return results;
    }

    /**
     * 财务报表
     *
     * @param param 检索对象
     * @param type  报表类型
     * @return
     */
    public List<FinanceResult> getFinanceReport(FinanceParam param, Integer type) {
        List<FinanceResult> list = financeMapper.getFinanceReport(param);
        // 对账客户 客户小计  总计    物料
        if (type == 1) {
        }
        // 对账明细 添加结算日期
        else if (type == 2) {
        }
        // 对账开票
        else if (type == 3) {
        }
        // 对账产品
        else if (type == 4) {
        }
        return null;
    }

    public Integer endDay(Integer Year, Integer Month) {
        switch (Month) {
            case 2:
                return (((Year & 3) == 0)
                        && ((Year % 100) != 0
                        || (Year % 400) == 0)) ? 29 : 28;
            case 4:
            case 6:
            case 9:
            case 11:
                return 30;
            default:
                return 31;
        }
    }

    @Override
    public List<Finance10Result> getCheckBalances(Finance10JcParam param) {

        /*获取9月余额*/
//        String startMonth = param.getMonth() - 1 < 10 ? "-0" + (param.getMonth() - 1) : "-" + (param.getMonth() - 1);
//        String endMonth = param.getMonth() < 10 ? "-0" + param.getMonth() : "-" + param.getMonth();
//        LocalDateTime startDate = LocalDateTimeUtil.parse(param.getYear() + startMonth + "-26T00:00:00");
//        LocalDateTime endDate = LocalDateTimeUtil.parse(param.getYear() + startMonth + "-" + endDay(param.getYear(),param.getMonth()-1) + "T23:59:59");
//        LocalDateTime endSettlementDate = LocalDateTimeUtil.parse(param.getYear() +endMonth + "-"  + "25T23:59:59");
//        yueParam yueParam = new yueParam();
//        yueParam.setCustomerUserId(param.getSupplierId());
//        yueParam.setStartMonthDate(startDate);
//        yueParam.setEndMonthDate(endDate);
//        yueParam.setStartSettlementDate(startDate);
//        yueParam.setEndSettlementDate(endSettlementDate);
//        yueParam.setCustomerUserId(param.getSupplierId());
//        yueParam.setSettlementMonth(param.getYear()+endMonth);
//        List<MonthlyBalanceBo> monthlyBalanceBos = financeMapper.getMonthlyBalanceBo(yueParam);
//        for (MonthlyBalanceBo monthlyBalanceBo:monthlyBalanceBos) {
//            monthlyBalanceBo.setBalanceDate(yueParam.getSettlementMonth());
//            LocalDateTime dateTime = LocalDateTime.now();
//            monthlyBalanceBo.setCreatedTime(dateTime);
//            monthlyBalanceBo.setEndingBalance(monthlyBalanceBo.getOpeningBalance().add(monthlyBalanceBo.getBilling().add(monthlyBalanceBo.getEndMonthBilling())).subtract(monthlyBalanceBo.getPayment()));
//            financeMapper.getInsertSupplier(monthlyBalanceBo);
//        }
        /*获取余额*/
        List<Finance10Result> results = new ArrayList<>();
        String startMonth = param.getMonth() - 1 < 10 ? "-0" + (param.getMonth() - 1) : "-" + (param.getMonth() - 1);
        String endMonth = param.getMonth() < 10 ? "-0" + param.getMonth() : "-" + param.getMonth();
        LocalDateTime startDate = LocalDateTimeUtil.parse(param.getYear() + startMonth + "-26T00:00:00");
        LocalDateTime endDate = LocalDateTimeUtil.parse(param.getYear() + startMonth + "-" + endDay(param.getYear(), param.getMonth() - 1) + "T23:59:59");
        LocalDateTime startDate1 = LocalDateTimeUtil.parse(param.getYear() + endMonth + "-26T00:00:00");
        LocalDateTime endDate1 = LocalDateTimeUtil.parse(param.getYear() + endMonth + "-" + endDay(param.getYear(), param.getMonth()) + "T23:59:59");
        LocalDateTime endDate2 = LocalDateTimeUtil.parse(param.getYear() + endMonth + "-" + "25T23:59:59");
        yueParam yueParam = new yueParam();
        yueParam.setSettlementMonth(param.getYear().toString() + "" + endMonth);
        yueParam.setCategoryId(param.getCategoryId());
        yueParam.setMaterialId(param.getMaterialId());
        yueParam.setCustomerUserId(param.getSupplierId());
        yueParam.setStartMonthDate(startDate1);
        yueParam.setEndMonthDate(endDate1);
        yueParam.setTb2startDate(startDate);
        yueParam.setTb2endDate(endDate);
        List<MonthlyBalanceBo> monthlyBalanceBos = financeMapper.getMonthlyBalanceResults(yueParam);
        if (monthlyBalanceBos != null && monthlyBalanceBos.size() > 0) {
            for (MonthlyBalanceBo monthlyBalanceBo : monthlyBalanceBos) {
                Finance10Result finance10Result = new Finance10Result();
                // 公司名称
                finance10Result.setCompanyName(monthlyBalanceBo.getCompanyName());
                // 入账单
                finance10Result.setCashRemittance(monthlyBalanceBo.getBilling());
                //货款
                finance10Result.setPaymentForGoods(monthlyBalanceBo.getPayment());
                // 余额
                finance10Result.setBalance(monthlyBalanceBo.getEndingBalance());
                // 上期余额
                finance10Result.setBeforeBalance(monthlyBalanceBo.getOpeningBalance());
                // 实时余额
                finance10Result.setCustomerCredit(monthlyBalanceBo.getCustomerCredit());
                results.add(finance10Result);
            }
        } else {
            yueParam = new yueParam();
            yueParam.setSettlementMonth(param.getYear().toString() + "" + endMonth);
            yueParam.setSettlementMonth1(param.getYear().toString() + "" + startMonth);
            yueParam.setCategoryId(param.getCategoryId());
            yueParam.setMaterialId(param.getMaterialId());
            yueParam.setCustomerUserId(param.getSupplierId());
            yueParam.setStartMonthDate(startDate);
            yueParam.setEndMonthDate(endDate);
            yueParam.setStartSettlementDate(startDate);
            yueParam.setEndSettlementDate(endDate1);
//            yueParam.setTb2startDate(startDate1);
//            yueParam.setTb2endDate(endDate1);
            monthlyBalanceBos = financeMapper.getMonthlyBalanceBo1(yueParam);
            for (MonthlyBalanceBo monthlyBalanceBo : monthlyBalanceBos) {
                Finance10Result finance10Result = new Finance10Result();
                // 公司名称
                finance10Result.setCompanyName(monthlyBalanceBo.getCompanyName());
                // 入账单
                finance10Result.setCashRemittance(monthlyBalanceBo.getBilling());
                //货款
                finance10Result.setPaymentForGoods(monthlyBalanceBo.getPayment());
                // 余额
                finance10Result.setBalance(monthlyBalanceBo.getEndingBalance());
                // 上期余额
                finance10Result.setBeforeBalance(monthlyBalanceBo.getOpeningBalance());
                // 实时余额
                finance10Result.setCustomerCredit(monthlyBalanceBo.getCustomerCredit());
                results.add(finance10Result);
            }
        }

        /*10月余额*/
//        List<MonthlyBalanceBo> monthlyBalanceBos = financeMapper.getMonthlyBalanceBos();
//        for (MonthlyBalanceBo finance10Result : monthlyBalanceBos) {
//            Integer supplierId =finance10Result.getSupplierId();
//            yueParam yueParam = new yueParam();
//            yueParam.setTb2startDate(LocalDateTimeUtil.parse("2021-09-26T00:00:00"));
//            yueParam.setTb2endDate(LocalDateTimeUtil.parse("2021-10-25T23:59:59"));
//            yueParam.setTb1endDate("2021-10");
//            System.out.println("System.out.println;" + supplierId);
//            yueParam.setCustomerUserId(supplierId);
//            MonthlyBalanceBo monthlyBalanceBo = new MonthlyBalanceBo();
//            // 获取上一个月的余额记录
//            MonthlyBalanceBo  monthlyBalanceBoss = financeMapper.getTb1Tb2(yueParam);
//            //获取 9月底的入账单
//            MonthlyBalanceBo monthlyBalanceBo2 = financeMapper.getBill(supplierId);
//            // 货款
//            if (monthlyBalanceBoss!=null&&monthlyBalanceBoss.getPayment()!=null&&monthlyBalanceBoss.getPayment().compareTo(new BigDecimal(0))!=0){
//                monthlyBalanceBo.setPayment(monthlyBalanceBoss.getPayment());
//            }
//            // 入账单
//            if (monthlyBalanceBoss!=null&&monthlyBalanceBoss.getBilling()!=null&&monthlyBalanceBoss.getBilling().compareTo(new BigDecimal(0))!=0){
//                monthlyBalanceBo.setBilling(monthlyBalanceBoss.getBilling());
//            }
//            //公司id
//            monthlyBalanceBo.setSupplierId(supplierId);
//            // 公司名称
//            monthlyBalanceBo.setCompanyName(finance10Result.getCompanyName());
//            // 余额日期
//            monthlyBalanceBo.setBalanceDate("2021-10");
//            // 期初余额
//            monthlyBalanceBo.setOpeningBalance(finance10Result.getEndingBalance());
//            if (monthlyBalanceBo2 != null  ){
//                monthlyBalanceBo.setEndingBalance(monthlyBalanceBo.getOpeningBalance().add(monthlyBalanceBo.getBilling().add(monthlyBalanceBo2.getBilling())).subtract(monthlyBalanceBo.getPayment()));
//            }else{
//                monthlyBalanceBo.setEndingBalance(monthlyBalanceBo.getOpeningBalance().add(monthlyBalanceBo.getBilling()).subtract(monthlyBalanceBo.getPayment()));
//            }
//            LocalDateTime dateTime = LocalDateTime.now();
//            monthlyBalanceBo.setCreatedTime(dateTime);
//            financeMapper.getInsertSupplier(monthlyBalanceBo);
//        }
        return results;
    }
}